amounts 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 9a77f5a9506149f307e11d78c1063e9951c149302eaace9b35e924cf92ce4102
4
- data.tar.gz: ade0b4aca169538a4b9e17d3e4ab412f19cbe343aff7b540de6936b814373751
3
+ metadata.gz: 1bcdc8db0e926c26c1aa8c46d67056bc9c10a109cf9b9622ca747d4819506173
4
+ data.tar.gz: d3cfb48d0f0d030ca3fa83df0f3a8a0d71bf11b19de5fe2b95870758c273caf2
5
5
  SHA512:
6
- metadata.gz: 0c9225c174016b40143bd049c8673312a0ceffcb32244b5ce9a613cdb2342d768faf67141ea0aeb30fe5c91d89bbf720860dae27fb77413e401d9e1877723b9b
7
- data.tar.gz: 1c0dd2ff180fc3589c4a722bd0789e37b9afb7d71599680c77fcd299b2e07366df31d439647c5927ff9a8f50d1d89c07ec8de1da05fae72d9570be78e8731020
6
+ metadata.gz: 3cd1e9bb7282f1c8e7ca3f3f4c7b4ce431b3fdc818e9e21cb08943e332b9f47456b2388aa931c5ec62b311d94fe767167b0ea421111a72a667611575b407c315
7
+ data.tar.gz: 6ef755ff9eb20f5da1f6ac948598a8a09186c160035adfe480ba93fc26dc314cf2f25fcbe841ecce9cc946a24542bef31f4f6e8b66c30176825cf6db24f3b80e
data/CHANGELOG.md CHANGED
@@ -1,5 +1,33 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0 - 2026-11-15
4
+
5
+ ### Added
6
+
7
+ - `Amount.manifest(locales: [])` exports the registry as a JSON-ready Hash for
8
+ a client in another language to mirror: every type (with the
9
+ `Amount.register` option names), every default rate as an exact decimal
10
+ string, and for each requested locale every translation the core looks up,
11
+ already resolved. The new `@zarpay/amounts` JavaScript client is built from
12
+ it. Locales need I18n.
13
+ - `Amount::Registry#default_rates` returns every registered default rate,
14
+ keyed by `[from, to]`.
15
+ - `Amount::Compact.locale_format(locale)` is public.
16
+
17
+ ### Fixed
18
+
19
+ - **Breaking:** `ui` and `to_s` round negative amounts by magnitude, like
20
+ their positive. `direction: :floor` (the default) now rounds toward zero and
21
+ `:ceil` away from it; before, `:floor` rounded toward negative infinity, so
22
+ a negative displayed more than it was (`-1.234` showed as `$-1.24`, and
23
+ `-0.001` as `$-0.01`). It now shows `$-1.23` and `$0.00`, and a value that
24
+ rounds to zero has no sign. Compact notation follows (`-1_999_999` is
25
+ `-1.99M`, was `-2M`). Positive amounts are unchanged. This matches `*`, `/`,
26
+ `to`, `split` and `allocate`, which already truncate toward zero. Migration:
27
+ code or tests that expect the old output for an inexact negative amount
28
+ should expect its positive's digits; pass `direction: :ceil` for the
29
+ larger magnitude.
30
+
3
31
  ## 0.2.0 - 2026-11-14
4
32
 
5
33
  ### Added
data/README.md CHANGED
@@ -422,6 +422,26 @@ Amount.of_usdc("1.5").as_json # => "USDC|1.500000"
422
422
  { amount: Amount.of_usdc("1.5") }.to_json # => '{"amount":"USDC|1.500000"}'
423
423
  ```
424
424
 
425
+ ### JavaScript client
426
+
427
+ `Amount.manifest` exports the registry for the
428
+ [`@zarpay/amounts`](../client) JavaScript client, which mirrors the core on the
429
+ web and in React Native: the same parsing, math, conversions, serialization
430
+ and display, on `bigint` atomic values.
431
+
432
+ ```ruby
433
+ render json: Amount.manifest(locales: I18n.available_locales)
434
+ ```
435
+
436
+ ```ts
437
+ const amounts = Amounts.fromManifest(manifest);
438
+ amounts.parse("USDC|1.500000").add(amounts.of("USDC", "0.25")).ui(); // "$1.75"
439
+ ```
440
+
441
+ The manifest holds the types (with the `Amount.register` option names), the
442
+ default rates as exact decimal strings, and for each requested locale every
443
+ translation the core looks up. Locales need I18n.
444
+
425
445
  ## Registry API
426
446
 
427
447
  ```ruby
@@ -429,9 +449,11 @@ Amount.register(...)
429
449
  Amount.register_default_rate(:USD, :USDC, "1")
430
450
  Amount.registry.lookup(:USDC)
431
451
  Amount.registry.symbols
452
+ Amount.registry.default_rates
432
453
  Amount.registry.clear!
433
454
  Amount.registry.lock!
434
455
  Amount.registry.locked?
456
+ Amount.manifest(locales: %i[en de])
435
457
  ```
436
458
 
437
459
  ## ActiveRecord Integration
@@ -654,14 +676,20 @@ bundle exec rspec
654
676
 
655
677
  ## Releases
656
678
 
657
- RubyGems publishing is intended to run from GitHub Releases using RubyGems trusted publishing.
679
+ The gem and the [`@zarpay/amounts`](../client) JavaScript client are versioned in lockstep and
680
+ released together from one GitHub Release, both through trusted publishing.
658
681
 
659
682
  Workflow:
660
683
 
661
- - create and push a version tag such as `v0.0.1`
684
+ - bump `Amount::VERSION` and `client/package.json` to the same version (CI fails when they
685
+ differ), and date both changelogs
686
+ - create and push a version tag such as `v0.3.0`
662
687
  - publish a GitHub Release for that tag
663
- - GitHub Actions runs `.github/workflows/release.yml`
664
- - the workflow verifies the test suite and publishes the gem to RubyGems.org
688
+ - GitHub Actions runs `.github/workflows/release.yml`, which verifies the test suite and
689
+ publishes the gem to RubyGems.org
690
+ - and `.github/workflows/publish-npm.yml`, which verifies the tag against both versions, runs
691
+ the client's checks and publishes `@zarpay/amounts` to npm with provenance (skipping a
692
+ version that's already on npm)
665
693
 
666
694
  RubyGems setup:
667
695
 
@@ -671,9 +699,18 @@ RubyGems setup:
671
699
  - workflow filename: `release.yml`
672
700
  - GitHub Actions environment: `release`
673
701
 
674
- This uses OIDC trusted publishing, so no RubyGems API token needs to be stored in GitHub Actions. See the official RubyGems trusted publishing guide:
702
+ npm setup:
703
+
704
+ - the first version of `@zarpay/amounts` is published once by hand (`npm publish --access public`
705
+ from `client/`), since npm can only attach a trusted publisher to a package that exists
706
+ - on npmjs.com, in the package's settings, add a trusted publisher: GitHub Actions, organization
707
+ `zarpay`, repository `amounts`, workflow filename `publish-npm.yml`, environment `release`
708
+
709
+ This uses OIDC trusted publishing on both registries, so no API token needs to be stored in
710
+ GitHub Actions. See the official guides:
675
711
 
676
712
  - https://guides.rubygems.org/trusted-publishing/
713
+ - https://docs.npmjs.com/trusted-publishers
677
714
 
678
715
  ## Compared to `money`
679
716
 
@@ -117,6 +117,10 @@ class Amount
117
117
  Formattable.fill(locale_format(locale), number:, label: word)
118
118
  end
119
119
 
120
+ # The template joining a compacted number and its scale word in `locale`:
121
+ # `number.human.decimal_units.format` when it places `%n`, else `"%n %u"`.
122
+ # @param locale [Symbol, String]
123
+ # @return [String]
120
124
  def locale_format(locale)
121
125
  found = Locale.translate(LOCALE_FORMAT_KEY, locale, LOCALE_FORMAT)
122
126
  Formattable.valid_template?(found) ? found : LOCALE_FORMAT
@@ -132,6 +136,6 @@ class Amount
132
136
  raise ArgumentError, "compact: precision must be a positive Integer, got #{digits.inspect}"
133
137
  end
134
138
 
135
- private_class_method :round, :number, :join, :locale_format, :precision_from_hash
139
+ private_class_method :round, :number, :join, :precision_from_hash
136
140
  end
137
141
  end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Amount
4
+ # Concern: exporting the registry for a client in another language to
5
+ # mirror. See {Manifest} for what the export holds.
6
+ module Exportable
7
+ def self.included(base)
8
+ base.extend(ClassMethods)
9
+ end
10
+
11
+ # Class-level methods extended onto any class that does `include Exportable`.
12
+ module ClassMethods
13
+ # The registry as a JSON-ready manifest: its types, its default rates,
14
+ # and for each locale in `locales` every translation the core looks up.
15
+ # The `@zarpay/amounts` JavaScript client is built from it.
16
+ #
17
+ # @param locales [Array<Symbol, String>] locales to resolve (needs I18n)
18
+ # @return [Hash{String=>Object}]
19
+ # @raise [ArgumentError] when locales are given without I18n loaded
20
+ # @example
21
+ # Amount.manifest["types"]["USDC"]["decimals"]
22
+ # # => 6
23
+ #
24
+ # @example Serving it from a Rails controller
25
+ # render json: Amount.manifest(locales: I18n.available_locales)
26
+ def manifest(locales: [])
27
+ Manifest.new(registry, locales:).to_h
28
+ end
29
+ end
30
+ end
31
+ end
@@ -6,16 +6,19 @@ class Amount
6
6
  # Formats amounts for UI output without changing their type.
7
7
  class Display
8
8
  # Rounds to `decimals` places (negative rounds to tens, hundreds, ...),
9
- # down with `:floor` and up with `:ceil`, like `ui`'s `direction:`.
9
+ # like `ui`'s `direction:`. The direction is by magnitude: `:floor` rounds
10
+ # toward zero and `:ceil` away from it, so a negative amount rounds like
11
+ # its positive and never displays more than it is. The rounded value is
12
+ # never negative zero.
10
13
  # @param value [BigDecimal]
11
14
  # @param decimals [Integer]
12
15
  # @param direction [Symbol]
13
16
  # @return [BigDecimal]
14
17
  def self.round(value, decimals, direction)
15
18
  factor = BigDecimal(10)**decimals
16
- scaled = value * factor
17
- truncated = direction == :ceil ? scaled.ceil : scaled.floor
18
- truncated / factor
19
+ scaled = value.abs * factor
20
+ magnitude = direction == :ceil ? scaled.ceil : scaled.floor
21
+ (value.negative? ? -magnitude : magnitude) / factor
19
22
  end
20
23
 
21
24
  # @param amount [Amount]
@@ -0,0 +1,128 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Amount
4
+ # Writes a registry as a manifest: a JSON-ready Hash with everything the
5
+ # core reads at runtime, for a client in another language to mirror (the
6
+ # `@zarpay/amounts` JavaScript client reads it).
7
+ #
8
+ # Types are written with the `Amount.register` option names. Every I18n
9
+ # lookup the core makes is resolved for each requested locale, so a client
10
+ # needs neither I18n nor its key conventions. The fallbacks (a missing label
11
+ # to `display_symbol`, a missing format to the registered template) are left
12
+ # to the client, which applies them as the gem does.
13
+ #
14
+ # @example
15
+ # Amount::Manifest.new(Amount.registry, locales: [:de]).to_h["types"]["USD"]["decimals"]
16
+ # # => 2
17
+ class Manifest
18
+ VERSION = 1
19
+
20
+ # @param registry [Amount::Registry]
21
+ # @param locales [Array<Symbol, String>] locales to resolve (needs I18n)
22
+ # @raise [ArgumentError] when locales are given without I18n loaded
23
+ def initialize(registry, locales: [])
24
+ Locale.require_i18n! unless locales.empty?
25
+
26
+ @registry = registry
27
+ @locales = locales
28
+ end
29
+
30
+ # @return [Hash{String=>Object}]
31
+ def to_h
32
+ {
33
+ "v" => VERSION,
34
+ "types" => @registry.symbols.to_h { |symbol| [symbol.to_s, type(@registry.lookup(symbol))] },
35
+ "rates" => @registry.default_rates.map { |(from, to), rate| rate_row(from, to, rate) },
36
+ "locales" => @locales.to_h { |locale| [locale.to_s, locale_table(locale)] }
37
+ }
38
+ end
39
+
40
+ private
41
+
42
+ def type(entry)
43
+ {
44
+ "decimals" => entry.decimals,
45
+ "display_symbol" => label(entry.display_symbol),
46
+ "display_format" => entry.display_format,
47
+ "ui_decimals" => entry.ui_decimals,
48
+ "trim_zeros" => entry.trim_zeros ? true : false,
49
+ "display_units" => entry.display_units&.to_h { |unit, spec| [unit.to_s, display_unit(spec)] },
50
+ "default_display" => entry.default_display&.to_s
51
+ }
52
+ end
53
+
54
+ def display_unit(spec)
55
+ {
56
+ "scale" => Amount.coerce_decimal(spec[:scale]).to_s("F"),
57
+ "symbol" => label(spec[:symbol]),
58
+ "ui_decimals" => spec[:ui_decimals],
59
+ "format" => spec[:format] || (spec[:position] && Formattable.template_for(spec[:position])),
60
+ "trim_zeros" => unit_trim_zeros(spec)
61
+ }
62
+ end
63
+
64
+ # `nil` when the unit doesn't set it, so the client falls back to the type.
65
+ def unit_trim_zeros(spec)
66
+ return unless spec.key?(:trim_zeros)
67
+
68
+ spec[:trim_zeros] ? true : false
69
+ end
70
+
71
+ def rate_row(from, to, rate)
72
+ { "from" => from.to_s, "to" => to.to_s, "rate" => rate.to_s("F") }
73
+ end
74
+
75
+ def locale_table(locale)
76
+ {
77
+ "number" => Locale.number_format(locale).transform_keys(&:to_s),
78
+ "compact" => compact_table(locale),
79
+ "types" => @registry.symbols.to_h { |symbol| [symbol.to_s, type_table(@registry.lookup(symbol), locale)] }
80
+ }
81
+ end
82
+
83
+ def compact_table(locale)
84
+ units = Compact::SCALES.to_h do |_, key, _|
85
+ [key.to_s, label(lookup("#{Compact::LOCALE_UNITS_KEY}.#{key}", locale))]
86
+ end
87
+
88
+ { "format" => Compact.locale_format(locale), "units" => units }
89
+ end
90
+
91
+ def type_table(entry, locale)
92
+ downcased = entry.symbol.to_s.downcase
93
+ units = (entry.display_units || {}).to_h do |unit, spec|
94
+ [unit.to_s, unit_table(downcased, unit, spec, locale)]
95
+ end
96
+
97
+ {
98
+ "label" => label(lookup(entry.label_key || "amounts.units.#{downcased}", locale)),
99
+ "format" => template(lookup("amounts.formats.#{downcased}", locale)),
100
+ "units" => units
101
+ }
102
+ end
103
+
104
+ def unit_table(downcased, unit, spec, locale)
105
+ {
106
+ "label" => label(lookup(spec[:label_key] || "amounts.display_units.#{downcased}.#{unit}", locale)),
107
+ "format" => template(lookup("amounts.display_unit_formats.#{downcased}.#{unit}", locale))
108
+ }
109
+ end
110
+
111
+ def lookup(key, locale)
112
+ ::I18n.t(key.to_s, locale:, default: nil)
113
+ end
114
+
115
+ # A String, or a plural Hash with String keys. Anything else is not a
116
+ # label the core could display, so it is written as `nil`.
117
+ def label(value)
118
+ case value
119
+ when String then value
120
+ when Hash then value.select { |_, form| form.is_a?(String) }.transform_keys(&:to_s)
121
+ end
122
+ end
123
+
124
+ def template(value)
125
+ value if Formattable.valid_template?(value)
126
+ end
127
+ end
128
+ end
@@ -223,6 +223,15 @@ class Amount
223
223
  @lock.synchronize { @default_rates.key?([from.to_sym, to.to_sym]) }
224
224
  end
225
225
 
226
+ # @return [Hash{Array(Symbol, Symbol)=>BigDecimal}] every registered
227
+ # default rate, keyed by `[from, to]`. A frozen copy.
228
+ # @example
229
+ # Amount.registry.default_rates
230
+ # # => { [:USD, :USDC] => 0.1e1 }
231
+ def default_rates
232
+ @lock.synchronize { @default_rates.dup.freeze }
233
+ end
234
+
226
235
  # @return [void]
227
236
  # @example Locking the global registry after initialization
228
237
  # Amount.registry.lock!
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  class Amount
4
- VERSION = "0.2.0"
4
+ VERSION = "0.3.0"
5
5
  end
data/lib/amount.rb CHANGED
@@ -14,6 +14,7 @@ require_relative "amount/compact"
14
14
  require_relative "amount/display"
15
15
  require_relative "amount/parser"
16
16
  require_relative "amount/ui_parser"
17
+ require_relative "amount/manifest"
17
18
 
18
19
  # Concerns: modules mixed into Amount. Files live in amount/concerns/, but the
19
20
  # constants are Amount::<Name> (the folder is not a namespace).
@@ -28,6 +29,7 @@ require_relative "amount/concerns/orderable"
28
29
  require_relative "amount/concerns/convertible"
29
30
  require_relative "amount/concerns/serializable"
30
31
  require_relative "amount/concerns/formattable"
32
+ require_relative "amount/concerns/exportable"
31
33
 
32
34
  # Represents a precise quantity of a registered fungible type.
33
35
  #
@@ -53,6 +55,8 @@ require_relative "amount/concerns/formattable"
53
55
  # - {Serializable} — `to_h`, `as_json`, `Amount.load`
54
56
  # - {Formattable} — `display_format(unit:, locale:)`, where the number and
55
57
  # unit go
58
+ # - {Exportable} — `Amount.manifest(locales:)`, the registry for a client
59
+ # in another language
56
60
  #
57
61
  # New behavior belongs in a concern, not in this class. See
58
62
  # `.claude/rules/concerns.md` for the shape a concern takes.
@@ -78,6 +82,7 @@ class Amount
78
82
  include Convertible
79
83
  include Serializable
80
84
  include Formattable
85
+ include Exportable
81
86
 
82
87
  extend Forwardable
83
88
 
@@ -123,22 +123,27 @@ class AmountCompactTest < Minitest::Test
123
123
  assert_equal "1T TOKENS", tokens(999_999_999_999).ui(compact: true, direction: :ceil)
124
124
  end
125
125
 
126
- # floor goes toward negative infinity, as `ui` does for any negative amount
126
+ # Rounding is by magnitude, as `ui` rounds any negative amount: a negative
127
+ # compacts like its positive, with a minus sign.
127
128
 
128
129
  def test_negative_exact_value
129
130
  assert_equal "-1.5M TOKENS", tokens(-1_500_000).ui(compact: true)
130
131
  end
131
132
 
132
- def test_negative_floor_rounds_away_from_zero
133
- assert_equal "-2M TOKENS", tokens(-1_999_999).ui(compact: true)
133
+ def test_negative_floor_rounds_toward_zero
134
+ assert_equal "-1.99M TOKENS", tokens(-1_999_999).ui(compact: true)
134
135
  end
135
136
 
136
- def test_negative_ceil_rounds_toward_zero
137
- assert_equal "-1.99M TOKENS", tokens(-1_999_999).ui(compact: true, direction: :ceil)
137
+ def test_negative_ceil_rounds_away_from_zero
138
+ assert_equal "-2M TOKENS", tokens(-1_999_999).ui(compact: true, direction: :ceil)
138
139
  end
139
140
 
140
- def test_negative_floor_rounds_into_the_next_scale
141
- assert_equal "-1M TOKENS", tokens(-999_999).ui(compact: true)
141
+ def test_negative_floor_stays_in_its_scale
142
+ assert_equal "-999K TOKENS", tokens(-999_999).ui(compact: true)
143
+ end
144
+
145
+ def test_negative_ceil_rounds_into_the_next_scale
146
+ assert_equal "-1M TOKENS", tokens(-999_999).ui(compact: true, direction: :ceil)
142
147
  end
143
148
 
144
149
  def test_negative_below_one_thousand_is_formatted_normally
@@ -336,6 +341,16 @@ class AmountCompactTest < Minitest::Test
336
341
  assert_equal "1,5 Tsd. TOKENS", tokens(1_500).ui(compact: true, locale: :de)
337
342
  end
338
343
 
344
+ def test_locale_format_reads_the_locale_template
345
+ store_decimal_units(:de, format: "%n%u", units: {})
346
+
347
+ assert_equal "%n%u", Amount::Compact.locale_format(:de)
348
+ end
349
+
350
+ def test_locale_format_defaults_without_a_template
351
+ assert_equal "%n %u", Amount::Compact.locale_format(:de)
352
+ end
353
+
339
354
  def test_compact_works_without_i18n
340
355
  without_i18n { assert_equal "50M TOKENS", tokens(50_000_000).ui(compact: true) }
341
356
  end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../../test_helper"
4
+ require_relative "../../support/locale_test_setup"
5
+
6
+ class AmountExportableTest < Minitest::Test
7
+ include LocaleTestSetup
8
+
9
+ def test_manifest_exports_the_global_registry
10
+ assert_equal Amount::Manifest.new(Amount.registry).to_h, Amount.manifest
11
+ end
12
+
13
+ def test_manifest_resolves_the_given_locales
14
+ assert_equal Amount::Manifest.new(Amount.registry, locales: [:de]).to_h, Amount.manifest(locales: [:de])
15
+ end
16
+
17
+ def test_manifest_follows_a_swapped_registry
18
+ exported = Amount.with_registry(Amount::Registry.new) do
19
+ Amount.register :TEST, decimals: 2
20
+ Amount.manifest
21
+ end
22
+
23
+ assert_equal %w[TEST], exported["types"].keys
24
+ end
25
+ end
@@ -39,6 +39,48 @@ class AmountDisplayTest < Minitest::Test
39
39
  assert_equal "$1.57", Amount.new("1.561", :USDC).ui(direction: :ceil)
40
40
  end
41
41
 
42
+ # Negatives round by magnitude: like their positive, with a minus sign.
43
+
44
+ def test_ui_negative_floor_rounds_toward_zero
45
+ assert_equal "$-1.56", Amount.new("-1.567", :USDC).ui
46
+ end
47
+
48
+ def test_ui_negative_ceil_rounds_away_from_zero
49
+ assert_equal "$-1.57", Amount.new("-1.561", :USDC).ui(direction: :ceil)
50
+ end
51
+
52
+ def test_ui_negative_rounding_to_zero_has_no_sign
53
+ assert_equal "$0.00", Amount.new("-0.001", :USDC).ui
54
+ end
55
+
56
+ def test_ui_negative_ceil_shows_the_smallest_unit
57
+ assert_equal "$-0.01", Amount.new("-0.001", :USDC).ui(direction: :ceil)
58
+ end
59
+
60
+ def test_ui_negative_display_unit_rounds_toward_zero
61
+ assert_equal "-31.10 g", Amount.new("-1", :GOLD).ui(unit: :gram)
62
+ end
63
+
64
+ def test_to_s_negative_rounds_toward_zero
65
+ assert_equal "USDC|-1.56", Amount.new("-1.567", :USDC).to_s
66
+ end
67
+
68
+ def test_to_s_negative_rounding_to_zero_has_no_sign
69
+ assert_equal "USDC|0.00", Amount.new("-0.001", :USDC).to_s
70
+ end
71
+
72
+ def test_round_negative_floor_toward_zero
73
+ assert_equal BigDecimal("-1.56"), Amount::Display.round(BigDecimal("-1.567"), 2, :floor)
74
+ end
75
+
76
+ def test_round_negative_ceil_away_from_zero
77
+ assert_equal BigDecimal("-1.57"), Amount::Display.round(BigDecimal("-1.561"), 2, :ceil)
78
+ end
79
+
80
+ def test_round_negative_to_tens_toward_zero
81
+ assert_equal BigDecimal("-120"), Amount::Display.round(BigDecimal("-129"), -1, :floor)
82
+ end
83
+
42
84
  # name => [expected, value, symbol]
43
85
  {
44
86
  "usdc" => ["1.50", "1.5", :USDC],
@@ -0,0 +1,325 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "../test_helper"
5
+ require_relative "../support/locale_test_setup"
6
+
7
+ class AmountManifestTest < Minitest::Test
8
+ include LocaleTestSetup
9
+
10
+ # Types
11
+
12
+ def test_version_is_one
13
+ assert_equal 1, manifest["v"]
14
+ end
15
+
16
+ def test_types_are_keyed_by_symbol
17
+ assert_equal %w[USDC USD SOL GOLD LOGS], manifest["types"].keys
18
+ end
19
+
20
+ def test_type_decimals
21
+ assert_equal 6, type("USDC")["decimals"]
22
+ end
23
+
24
+ def test_type_display_symbol
25
+ assert_equal "$", type("USDC")["display_symbol"]
26
+ end
27
+
28
+ def test_type_plural_display_symbol_has_string_keys
29
+ Amount.register :SEARCHES, decimals: 0, display_symbol: { one: "search", other: "searches" }
30
+
31
+ assert_equal({ "one" => "search", "other" => "searches" }, type("SEARCHES")["display_symbol"])
32
+ end
33
+
34
+ def test_type_display_format_is_the_resolved_template
35
+ assert_equal "%u%n", type("USDC")["display_format"]
36
+ end
37
+
38
+ def test_type_display_format_written_as_given
39
+ Amount.register :EUR, decimals: 2, display_symbol: "€", display_format: "%n %u"
40
+
41
+ assert_equal "%n %u", type("EUR")["display_format"]
42
+ end
43
+
44
+ def test_type_ui_decimals
45
+ assert_equal 2, type("USDC")["ui_decimals"]
46
+ end
47
+
48
+ def test_type_trim_zeros_defaults_to_false
49
+ assert_equal false, type("USDC")["trim_zeros"]
50
+ end
51
+
52
+ def test_type_trim_zeros_when_set
53
+ Amount.register :TOKENS, decimals: 0, trim_zeros: true
54
+
55
+ assert_equal true, type("TOKENS")["trim_zeros"]
56
+ end
57
+
58
+ def test_type_without_display_units
59
+ assert_nil type("USDC")["display_units"]
60
+ end
61
+
62
+ def test_type_default_display
63
+ assert_equal "oz_t", type("GOLD")["default_display"]
64
+ end
65
+
66
+ def test_type_without_default_display
67
+ assert_nil type("USDC")["default_display"]
68
+ end
69
+
70
+ # Display units
71
+
72
+ def test_display_units_are_keyed_by_unit
73
+ assert_equal %w[oz_t gram kg], type("GOLD")["display_units"].keys
74
+ end
75
+
76
+ def test_display_unit_scale_is_an_exact_string
77
+ assert_equal "31.1035", unit("GOLD", "gram")["scale"]
78
+ end
79
+
80
+ def test_display_unit_integer_scale
81
+ assert_equal "1.0", unit("GOLD", "oz_t")["scale"]
82
+ end
83
+
84
+ def test_display_unit_rational_scale_is_written_as_the_gem_uses_it
85
+ register_unit_type(third: { scale: Rational(1, 3) })
86
+
87
+ assert_equal "0.3333333333333333333", unit("UNITS", "third")["scale"]
88
+ end
89
+
90
+ def test_display_unit_symbol
91
+ assert_equal "g", unit("GOLD", "gram")["symbol"]
92
+ end
93
+
94
+ def test_display_unit_without_symbol
95
+ register_unit_type(plain: { scale: 1 })
96
+
97
+ assert_nil unit("UNITS", "plain")["symbol"]
98
+ end
99
+
100
+ def test_display_unit_ui_decimals
101
+ assert_equal 2, unit("GOLD", "gram")["ui_decimals"]
102
+ end
103
+
104
+ def test_display_unit_without_ui_decimals
105
+ register_unit_type(plain: { scale: 1 })
106
+
107
+ assert_nil unit("UNITS", "plain")["ui_decimals"]
108
+ end
109
+
110
+ def test_display_unit_format
111
+ register_unit_type(dozen: { scale: "0.083", format: "%n doz" })
112
+
113
+ assert_equal "%n doz", unit("UNITS", "dozen")["format"]
114
+ end
115
+
116
+ def test_display_unit_position_is_written_as_its_template
117
+ register_unit_type(dozen: { scale: "0.083", position: :prefix })
118
+
119
+ assert_equal "%u%n", unit("UNITS", "dozen")["format"]
120
+ end
121
+
122
+ def test_display_unit_without_format_or_position
123
+ assert_nil unit("GOLD", "gram")["format"]
124
+ end
125
+
126
+ def test_display_unit_trim_zeros_when_set
127
+ register_unit_type(plain: { scale: 1, trim_zeros: true })
128
+
129
+ assert_equal true, unit("UNITS", "plain")["trim_zeros"]
130
+ end
131
+
132
+ def test_display_unit_trim_zeros_set_to_false
133
+ register_unit_type(plain: { scale: 1, trim_zeros: false })
134
+
135
+ assert_equal false, unit("UNITS", "plain")["trim_zeros"]
136
+ end
137
+
138
+ def test_display_unit_without_trim_zeros
139
+ assert_nil unit("GOLD", "gram")["trim_zeros"]
140
+ end
141
+
142
+ # Rates
143
+
144
+ def test_without_rates
145
+ assert_empty manifest["rates"]
146
+ end
147
+
148
+ def test_rate_row
149
+ Amount.register_default_rate :USD, :USDC, "1"
150
+
151
+ assert_equal [{ "from" => "USD", "to" => "USDC", "rate" => "1.0" }], manifest["rates"]
152
+ end
153
+
154
+ def test_rational_rate_is_written_as_the_gem_uses_it
155
+ Amount.register_default_rate :USDC, :USD, Rational(1, 3)
156
+
157
+ assert_equal "0.3333333333333333333", manifest["rates"].first["rate"]
158
+ end
159
+
160
+ # Locales
161
+
162
+ def test_without_locales
163
+ assert_empty manifest["locales"]
164
+ end
165
+
166
+ def test_locales_are_keyed_by_locale
167
+ assert_equal %w[en de], manifest(locales: %i[en de])["locales"].keys
168
+ end
169
+
170
+ def test_locales_need_i18n
171
+ without_i18n do
172
+ assert_raises(ArgumentError) { manifest(locales: [:de]) }
173
+ end
174
+ end
175
+
176
+ def test_number_format
177
+ assert_equal({ "delimiter" => ".", "separator" => "," }, locale_table(:de)["number"])
178
+ end
179
+
180
+ def test_number_format_defaults
181
+ assert_equal({ "delimiter" => ",", "separator" => "." }, locale_table(:xx)["number"])
182
+ end
183
+
184
+ def test_compact_format_defaults
185
+ assert_equal "%n %u", locale_table(:de)["compact"]["format"]
186
+ end
187
+
188
+ def test_compact_format_translated
189
+ store(:de, number: { human: { decimal_units: { format: "%n%u" } } })
190
+
191
+ assert_equal "%n%u", locale_table(:de)["compact"]["format"]
192
+ end
193
+
194
+ def test_compact_format_without_number_falls_back
195
+ store(:de, number: { human: { decimal_units: { format: "%u" } } })
196
+
197
+ assert_equal "%n %u", locale_table(:de)["compact"]["format"]
198
+ end
199
+
200
+ def test_compact_units_list_every_scale
201
+ assert_equal %w[thousand million billion trillion quadrillion quintillion sextillion septillion
202
+ octillion nonillion decillion], locale_table(:de)["compact"]["units"].keys
203
+ end
204
+
205
+ def test_compact_unit_translated
206
+ store(:de, number: { human: { decimal_units: { units: { thousand: "Tsd." } } } })
207
+
208
+ assert_equal "Tsd.", locale_table(:de)["compact"]["units"]["thousand"]
209
+ end
210
+
211
+ def test_compact_unit_plural_forms
212
+ store(:de, number: { human: { decimal_units: { units: { million: { one: "Million", other: "Millionen" } } } } })
213
+
214
+ assert_equal({ "one" => "Million", "other" => "Millionen" }, locale_table(:de)["compact"]["units"]["million"])
215
+ end
216
+
217
+ def test_compact_unit_without_translation
218
+ assert_nil locale_table(:de)["compact"]["units"]["thousand"]
219
+ end
220
+
221
+ def test_type_label_without_translation
222
+ assert_nil locale_type(:de, "GOLD")["label"]
223
+ end
224
+
225
+ def test_type_label_translated
226
+ store(:de, amounts: { units: { gold: "Feinunze" } })
227
+
228
+ assert_equal "Feinunze", locale_type(:de, "GOLD")["label"]
229
+ end
230
+
231
+ def test_type_label_from_label_key
232
+ store(:de, coins: { searches: "Suchen" })
233
+ Amount.register :SEARCHES, decimals: 0, label_key: "coins.searches"
234
+
235
+ assert_equal "Suchen", locale_type(:de, "SEARCHES")["label"]
236
+ end
237
+
238
+ def test_type_label_plural_forms
239
+ store(:de, amounts: { units: { logs: { one: "Stamm", other: "Stämme" } } })
240
+
241
+ assert_equal({ "one" => "Stamm", "other" => "Stämme" }, locale_type(:de, "LOGS")["label"])
242
+ end
243
+
244
+ def test_type_format_translated
245
+ store(:de, amounts: { formats: { usd: "%n %u" } })
246
+
247
+ assert_equal "%n %u", locale_type(:de, "USD")["format"]
248
+ end
249
+
250
+ def test_type_format_without_number_is_ignored
251
+ store(:de, amounts: { formats: { usd: "%u" } })
252
+
253
+ assert_nil locale_type(:de, "USD")["format"]
254
+ end
255
+
256
+ def test_type_without_display_units_has_no_unit_tables
257
+ assert_empty locale_type(:de, "USD")["units"]
258
+ end
259
+
260
+ def test_unit_label_translated
261
+ store(:de, amounts: { display_units: { gold: { gram: "Gramm" } } })
262
+
263
+ assert_equal "Gramm", locale_type(:de, "GOLD")["units"]["gram"]["label"]
264
+ end
265
+
266
+ def test_unit_label_from_label_key
267
+ store(:de, metric: { gram: "Gramm" })
268
+ register_unit_type(gram: { scale: 1, label_key: "metric.gram" })
269
+
270
+ assert_equal "Gramm", locale_type(:de, "UNITS")["units"]["gram"]["label"]
271
+ end
272
+
273
+ def test_unit_label_without_translation
274
+ assert_nil locale_type(:de, "GOLD")["units"]["gram"]["label"]
275
+ end
276
+
277
+ def test_unit_format_translated
278
+ store(:de, amounts: { display_unit_formats: { gold: { gram: "%n %u" } } })
279
+
280
+ assert_equal "%n %u", locale_type(:de, "GOLD")["units"]["gram"]["format"]
281
+ end
282
+
283
+ def test_unit_format_without_translation
284
+ assert_nil locale_type(:de, "GOLD")["units"]["gram"]["format"]
285
+ end
286
+
287
+ # JSON
288
+
289
+ def test_survives_a_json_round_trip
290
+ Amount.register_default_rate :USD, :USDC, "1"
291
+ written = manifest(locales: [:de])
292
+
293
+ assert_equal written, JSON.parse(written.to_json)
294
+ end
295
+
296
+ private
297
+
298
+ def manifest(locales: [])
299
+ Amount::Manifest.new(Amount.registry, locales:).to_h
300
+ end
301
+
302
+ def type(symbol)
303
+ manifest["types"][symbol]
304
+ end
305
+
306
+ def unit(symbol, unit)
307
+ type(symbol)["display_units"][unit]
308
+ end
309
+
310
+ def locale_table(locale)
311
+ manifest(locales: [locale])["locales"][locale.to_s]
312
+ end
313
+
314
+ def locale_type(locale, symbol)
315
+ locale_table(locale)["types"][symbol]
316
+ end
317
+
318
+ def store(locale, translations)
319
+ I18n.backend.store_translations(locale, translations)
320
+ end
321
+
322
+ def register_unit_type(units)
323
+ Amount.register :UNITS, decimals: 2, display_units: units
324
+ end
325
+ end
@@ -79,6 +79,20 @@ class AmountRegistryTest < Minitest::Test
79
79
  assert_equal BigDecimal("0.5"), Amount.new("1", :USDC).to(:USD).decimal
80
80
  end
81
81
 
82
+ def test_default_rates_lists_each_rate_by_direction
83
+ Amount.register_default_rate :USD, :USDC, "1"
84
+
85
+ assert_equal({ %i[USD USDC] => BigDecimal("1") }, Amount.registry.default_rates)
86
+ end
87
+
88
+ def test_default_rates_is_empty_without_rates
89
+ assert_empty Amount.registry.default_rates
90
+ end
91
+
92
+ def test_default_rates_is_frozen
93
+ assert_predicate Amount.registry.default_rates, :frozen?
94
+ end
95
+
82
96
  def test_prefix_display_position_is_stored_as_its_template
83
97
  assert_equal "%u%n", Amount.registry.lookup(:USD).display_format
84
98
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: amounts
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.0
4
+ version: 0.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Seb Scholl
@@ -64,6 +64,7 @@ files:
64
64
  - lib/amount/concerns/coercible.rb
65
65
  - lib/amount/concerns/constructible.rb
66
66
  - lib/amount/concerns/convertible.rb
67
+ - lib/amount/concerns/exportable.rb
67
68
  - lib/amount/concerns/formattable.rb
68
69
  - lib/amount/concerns/localizable.rb
69
70
  - lib/amount/concerns/orderable.rb
@@ -72,6 +73,7 @@ files:
72
73
  - lib/amount/concerns/serializable.rb
73
74
  - lib/amount/display.rb
74
75
  - lib/amount/locale.rb
76
+ - lib/amount/manifest.rb
75
77
  - lib/amount/parser.rb
76
78
  - lib/amount/registry.rb
77
79
  - lib/amount/registry/generated_constructors.rb
@@ -103,6 +105,7 @@ files:
103
105
  - test/amount/concerns/coercible_test.rb
104
106
  - test/amount/concerns/constructible_test.rb
105
107
  - test/amount/concerns/convertible_test.rb
108
+ - test/amount/concerns/exportable_test.rb
106
109
  - test/amount/concerns/formattable_test.rb
107
110
  - test/amount/concerns/localizable_test.rb
108
111
  - test/amount/concerns/orderable_test.rb
@@ -111,6 +114,7 @@ files:
111
114
  - test/amount/concerns/serializable_test.rb
112
115
  - test/amount/display_test.rb
113
116
  - test/amount/locale_test.rb
117
+ - test/amount/manifest_test.rb
114
118
  - test/amount/parser_test.rb
115
119
  - test/amount/registry/generated_constructors_test.rb
116
120
  - test/amount/registry_test.rb