amounts 0.0.8 → 0.2.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.
Files changed (74) hide show
  1. checksums.yaml +4 -4
  2. data/.rubocop.yml +37 -0
  3. data/CHANGELOG.md +180 -0
  4. data/Gemfile +4 -0
  5. data/README.md +274 -2
  6. data/Rakefile +47 -10
  7. data/lib/amount/active_record/amount_validator.rb +9 -18
  8. data/lib/amount/active_record/attribute_definition.rb +14 -8
  9. data/lib/amount/active_record/calculations.rb +127 -0
  10. data/lib/amount/active_record/dirty.rb +43 -0
  11. data/lib/amount/active_record/locale/en.yml +7 -0
  12. data/lib/amount/active_record/model.rb +19 -3
  13. data/lib/amount/active_record/persistence.rb +34 -0
  14. data/lib/amount/active_record/serialization.rb +57 -0
  15. data/lib/amount/active_record.rb +18 -0
  16. data/lib/amount/compact.rb +137 -0
  17. data/lib/amount/{allocation.rb → concerns/allocatable.rb} +1 -1
  18. data/lib/amount/{arithmetic.rb → concerns/calculable.rb} +5 -2
  19. data/lib/amount/concerns/coercible.rb +65 -0
  20. data/lib/amount/concerns/constructible.rb +92 -0
  21. data/lib/amount/{conversion.rb → concerns/convertible.rb} +1 -1
  22. data/lib/amount/concerns/formattable.rb +112 -0
  23. data/lib/amount/concerns/localizable.rb +39 -0
  24. data/lib/amount/{comparison.rb → concerns/orderable.rb} +2 -2
  25. data/lib/amount/concerns/parsable.rb +58 -0
  26. data/lib/amount/concerns/registrable.rb +80 -0
  27. data/lib/amount/{serialization.rb → concerns/serializable.rb} +21 -4
  28. data/lib/amount/display.rb +81 -46
  29. data/lib/amount/locale.rb +102 -0
  30. data/lib/amount/registry.rb +69 -7
  31. data/lib/amount/ui_parser.rb +109 -0
  32. data/lib/amount/version.rb +1 -1
  33. data/lib/amount.rb +55 -199
  34. data/test/amount/active_record/amount_validator_test.rb +209 -0
  35. data/test/amount/active_record/attribute_definition_test.rb +259 -0
  36. data/test/amount/active_record/calculations_test.rb +165 -0
  37. data/test/amount/active_record/dirty_test.rb +70 -0
  38. data/test/amount/active_record/migration_methods_test.rb +60 -0
  39. data/test/amount/active_record/model_test.rb +72 -0
  40. data/test/amount/active_record/persistence_test.rb +53 -0
  41. data/test/amount/active_record/serialization_test.rb +75 -0
  42. data/test/amount/active_record/type_test.rb +80 -0
  43. data/test/amount/active_record_test.rb +12 -0
  44. data/test/amount/compact_test.rb +371 -0
  45. data/test/amount/concerns/allocatable_test.rb +166 -0
  46. data/test/amount/concerns/calculable_test.rb +185 -0
  47. data/test/amount/concerns/coercible_test.rb +49 -0
  48. data/test/amount/concerns/constructible_test.rb +113 -0
  49. data/test/amount/concerns/convertible_test.rb +54 -0
  50. data/test/amount/concerns/formattable_test.rb +336 -0
  51. data/test/amount/concerns/localizable_test.rb +59 -0
  52. data/test/amount/concerns/orderable_test.rb +83 -0
  53. data/test/amount/concerns/parsable_test.rb +98 -0
  54. data/test/amount/concerns/registrable_test.rb +67 -0
  55. data/test/amount/concerns/serializable_test.rb +136 -0
  56. data/test/amount/display_test.rb +181 -0
  57. data/test/amount/locale_test.rb +590 -0
  58. data/test/amount/parser_test.rb +29 -0
  59. data/test/amount/registry/generated_constructors_test.rb +94 -0
  60. data/test/amount/registry_test.rb +149 -0
  61. data/test/amount/ui_parser_test.rb +284 -0
  62. data/test/amount_test.rb +55 -0
  63. data/test/dummy/config/application.rb +3 -0
  64. data/test/generators/amount/active_record/registry_generator_test.rb +116 -0
  65. data/test/integration/postgresql_test.rb +124 -0
  66. data/test/support/active_record_test_support.rb +85 -0
  67. data/test/support/error_helpers.rb +22 -0
  68. data/test/support/locale_test_setup.rb +36 -0
  69. data/test/test_helper.rb +1 -0
  70. metadata +55 -11
  71. data/test/postgresql_integration_test.rb +0 -71
  72. data/test/test_active_record.rb +0 -375
  73. data/test/test_amount.rb +0 -675
  74. data/test/test_registry_generator.rb +0 -104
@@ -0,0 +1,92 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bigdecimal"
4
+
5
+ class Amount
6
+ # Concern: how a constructor input becomes an atomic `Integer`, and which
7
+ # class an amount is built as.
8
+ #
9
+ # Input inference rules:
10
+ # - `Integer` => atomic units
11
+ # - `String` => UI decimal value
12
+ # - `Float`, `BigDecimal`, `Rational` => UI decimal value (a `Float` goes
13
+ # through its string form, never through float math)
14
+ # - `from:` (`:atomic`, `:ui`, `:float`) overrides inference
15
+ #
16
+ # Class identity: a type registered with `class:` is always built as that
17
+ # class. `Amount.new` dispatches to it, and every operator that returns an
18
+ # amount goes through {#build} so the receiver's class carries through.
19
+ module Constructible
20
+ def self.included(base)
21
+ base.extend(ClassMethods)
22
+ end
23
+
24
+ # Class-level methods extended onto any class that does
25
+ # `include Constructible`.
26
+ module ClassMethods
27
+ # When called as `Amount.new` for a symbol whose registry entry binds a
28
+ # custom class, dispatch the construction to that class instead of
29
+ # raising. Direct calls to a subclass (`GoldAmount.new(...)`) still go
30
+ # through the default `Class.new` path. Calls that target the wrong
31
+ # subclass continue to raise from `#initialize`.
32
+ #
33
+ # @param value [Integer, String, Float, BigDecimal, Rational]
34
+ # @param symbol [Symbol, String]
35
+ # @param from [Symbol, nil]
36
+ # @return [Amount]
37
+ def new(value, symbol, from: nil)
38
+ if equal?(::Amount)
39
+ entry_class = registry.lookup(symbol.to_sym).amount_class
40
+ return entry_class.new(value, symbol, from:) if entry_class && entry_class != ::Amount
41
+ end
42
+ super
43
+ end
44
+ end
45
+
46
+ private
47
+
48
+ # Builds a same-symbol amount in the receiver's class. Used by every
49
+ # operator that returns an Amount so subclass identity propagates.
50
+ def build(atomic_value)
51
+ self.class.new(atomic_value, symbol, from: :atomic)
52
+ end
53
+
54
+ # A type registered with `class: GoldAmount` must be built as
55
+ # `GoldAmount` (or dispatched there by `Amount.new`), never as another
56
+ # subclass.
57
+ def ensure_registered_class!
58
+ expected = registry_entry.amount_class
59
+ return unless expected && expected != Amount && self.class != Amount && !instance_of?(expected)
60
+
61
+ raise InvalidInput, "use #{expected}.new for #{symbol}"
62
+ end
63
+
64
+ def infer_value(from, value)
65
+ case from || infer_type(value)
66
+ when :atomic then value.to_i
67
+ when :ui then ui_to_atomic(value)
68
+ when :float then ui_to_atomic(value.is_a?(Rational) ? value : value.to_s)
69
+ else
70
+ raise InvalidInput, "unknown amount format: #{value.inspect}"
71
+ end
72
+ end
73
+
74
+ def infer_type(value)
75
+ case value
76
+ when Integer then :atomic
77
+ when String then :ui
78
+ when Float, BigDecimal, Rational then :float
79
+ else
80
+ raise InvalidInput, "cannot infer type for #{value.class}"
81
+ end
82
+ end
83
+
84
+ def ui_to_atomic(value)
85
+ return (value * (10**decimals)).to_i if value.is_a?(Rational)
86
+
87
+ (BigDecimal(value.to_s) * (BigDecimal(10)**decimals)).to_i
88
+ rescue ArgumentError
89
+ raise InvalidInput, "cannot parse #{value.inspect} as #{symbol}"
90
+ end
91
+ end
92
+ end
@@ -6,7 +6,7 @@ class Amount
6
6
  # default rate. The result class is taken from the target symbol's registry
7
7
  # entry, so a `class:`-registered subclass becomes the natural identity for
8
8
  # conversion outputs.
9
- module Conversion
9
+ module Convertible
10
10
  # @param target_symbol [Symbol, String]
11
11
  # @param rate [String, Numeric, BigDecimal, nil]
12
12
  # @return [Amount]
@@ -0,0 +1,112 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Amount
4
+ # Concern: where the number and its unit label go in decorated output.
5
+ #
6
+ # A format is a template in the style of Rails' `number.currency.format.format`:
7
+ # `%n` is the formatted number (sign included) and `%u` the unit label.
8
+ # Everything else is copied as given, so a non-breaking space in
9
+ # `"%n %u"` stays non-breaking.
10
+ #
11
+ # Included in {Amount}, it answers one question per amount, {#display_format}:
12
+ # which template does decorated `ui` output use, for this type or one of its
13
+ # display units, in this locale? The module functions are the template
14
+ # primitives the registry (validation) and {Display} (filling) share.
15
+ #
16
+ # A template is resolved, first match wins:
17
+ #
18
+ # - type: `amounts.formats.<symbol downcased>` (when localizing), then the
19
+ # registered `display_format`, which the registry derives from
20
+ # `display_position` when no template was given.
21
+ # - display unit: `amounts.display_unit_formats.<symbol downcased>.<unit>`
22
+ # (when localizing), then the unit's `:format`, then its `:position`, then
23
+ # the type's template as above.
24
+ #
25
+ # A locale template without `%n` is ignored, so a typo in a locale file can't
26
+ # drop the amount from the output.
27
+ #
28
+ # @example
29
+ # Amount.register :EUR, decimals: 2, display_symbol: "€", display_format: "%u%n"
30
+ # # de.yml: amounts.formats.eur: "%n %u"
31
+ #
32
+ # Amount.of_eur("1").display_format # => "%u%n"
33
+ # Amount.of_eur("1").display_format(locale: :de) # => "%n %u"
34
+ # Amount::Formattable.fill("%n %u", number: "12,50", label: "€")
35
+ # # => "12,50 €"
36
+ module Formattable
37
+ NUMBER = "%n"
38
+ LABEL = "%u"
39
+ PREFIX = "%u%n"
40
+ SUFFIX = "%n %u"
41
+
42
+ PLACEHOLDER = /%[nu]/
43
+ private_constant :PLACEHOLDER
44
+
45
+ # The template a `display_position` stands for: `:prefix` is `"%u%n"`,
46
+ # anything else `"%n %u"`, matching the output before templates existed.
47
+ # @param position [Symbol, nil]
48
+ # @return [String]
49
+ def self.template_for(position)
50
+ position == :prefix ? PREFIX : SUFFIX
51
+ end
52
+
53
+ # A usable template is a String that places the number.
54
+ # @param template [Object]
55
+ # @return [Boolean]
56
+ def self.valid_template?(template)
57
+ template.is_a?(String) && template.include?(NUMBER)
58
+ end
59
+
60
+ # Fills a template in one pass, so a `%` inside the number or label is
61
+ # never read as a placeholder.
62
+ # @param template [String]
63
+ # @param number [String] the formatted number
64
+ # @param label [String] the unit label
65
+ # @return [String]
66
+ def self.fill(template, number:, label:)
67
+ template.gsub(PLACEHOLDER, NUMBER => number, LABEL => label)
68
+ end
69
+
70
+ # The template decorated `ui` output uses for this amount.
71
+ #
72
+ # @param unit [Symbol, nil] a display unit, or `nil` for the type itself
73
+ # @param locale [Symbol, String, nil] look for a locale template too
74
+ # (requires I18n). When `nil`, uses `I18n.locale` if `Amount.localize`
75
+ # is true, else only the registered templates.
76
+ # @return [String]
77
+ # @raise [Registry::InvalidDisplayUnit] for an unknown display unit
78
+ # @example
79
+ # Amount.of_usd("1").display_format # => "%u%n"
80
+ # Amount.of_gold("1").display_format(unit: :gram) # => "%n %u"
81
+ def display_format(unit: nil, locale: nil)
82
+ locale = Locale.effective(locale)
83
+ return type_display_format(locale) unless unit
84
+
85
+ spec = registry_entry.display_unit(unit)
86
+ (locale && locale_display_format(unit_format_key(unit), locale)) ||
87
+ spec[:format] ||
88
+ (spec[:position] && Formattable.template_for(spec[:position])) ||
89
+ type_display_format(locale)
90
+ end
91
+
92
+ private
93
+
94
+ def type_display_format(locale)
95
+ (locale && locale_display_format(type_format_key, locale)) ||
96
+ registry_entry.display_format
97
+ end
98
+
99
+ def locale_display_format(key, locale)
100
+ found = Locale.translate(key, locale, nil)
101
+ found if Formattable.valid_template?(found)
102
+ end
103
+
104
+ def type_format_key
105
+ "amounts.formats.#{symbol.to_s.downcase}"
106
+ end
107
+
108
+ def unit_format_key(unit)
109
+ "amounts.display_unit_formats.#{symbol.to_s.downcase}.#{unit}"
110
+ end
111
+ end
112
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Amount
4
+ # Concern: the global switch that makes output and input follow
5
+ # `I18n.locale` when no `locale:` is given.
6
+ #
7
+ # Every locale-aware method (`ui`, `unit_label`, `display_format`,
8
+ # `Amount.parse_ui`) resolves its locale through {Locale.effective}, which
9
+ # reads this switch.
10
+ #
11
+ # @example
12
+ # Amount.localize = true
13
+ # I18n.locale = :de
14
+ # Amount.of_usd("1500.5").ui # formatted with de's number.format
15
+ module Localizable
16
+ def self.included(base)
17
+ base.extend(ClassMethods)
18
+ end
19
+
20
+ # Class-level methods extended onto any class that does
21
+ # `include Localizable`.
22
+ module ClassMethods
23
+ # Whether `ui` formats numbers for `I18n.locale` when no `locale:` is
24
+ # given. Defaults to `false`.
25
+ # @return [Boolean]
26
+ def localize?
27
+ @localize ? true : false
28
+ end
29
+ alias localize localize?
30
+
31
+ # @param value [Boolean]
32
+ # @raise [ArgumentError] when enabling without I18n loaded
33
+ def localize=(value)
34
+ Locale.require_i18n! if value
35
+ @localize = value ? true : false
36
+ end
37
+ end
38
+ end
39
+ end
@@ -3,10 +3,10 @@
3
3
  class Amount
4
4
  # Comparison, equality, hashing, and sign predicates for `Amount`.
5
5
  #
6
- # Pulls in `Comparable` itself so consumers only need `include Comparison`
6
+ # Pulls in `Comparable` itself so consumers only need `include Orderable`
7
7
  # to get `<`, `<=`, `>`, `>=`, `between?`, `clamp`, and `Enumerable#min`/
8
8
  # `#max` alongside the explicit `<=>` / `==` / `eql?` / `hash` defined here.
9
- module Comparison
9
+ module Orderable
10
10
  include Comparable
11
11
  # @param other [Object]
12
12
  # @return [Boolean]
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Amount
4
+ # Concern: the class-level entry points that turn strings into amounts.
5
+ #
6
+ # Two inputs, two parsers:
7
+ #
8
+ # - {Amount.parse} reads the compact machine format (`USDC|1.50`) that
9
+ # `to_s` writes. See {Parser}.
10
+ # - {Amount.parse_ui} reads what a person typed, in a locale's number
11
+ # format. See {UiParser}.
12
+ module Parsable
13
+ def self.included(base)
14
+ base.extend(ClassMethods)
15
+ end
16
+
17
+ # Class-level methods extended onto any class that does `include Parsable`.
18
+ module ClassMethods
19
+ # Parses the compact client-facing string representation.
20
+ #
21
+ # Accepts either the default form `SYMBOL|amount` or the explicit
22
+ # versioned form `v1:SYMBOL|amount`.
23
+ #
24
+ # @param str [String]
25
+ # @return [Amount]
26
+ # @raise [InvalidInput]
27
+ # @example Parsing the default compact format
28
+ # Amount.parse("USDC|1.50")
29
+ #
30
+ # @example Parsing the explicit versioned compact format
31
+ # Amount.parse("v1:USDC|1.50")
32
+ def parse(str)
33
+ Parser.new(str).parse
34
+ end
35
+
36
+ # Parses text typed by a person, in a locale's number format.
37
+ #
38
+ # The effective locale is `locale:`, then `I18n.locale` when
39
+ # `Amount.localize` is true, else plain parsing (`.` decimal, no
40
+ # delimiters). Accepts surrounding whitespace, a leading `-` or `+`,
41
+ # delimiters in groups of three, and the type's label (any plural form)
42
+ # at either end. Never rounds.
43
+ #
44
+ # @param input [String]
45
+ # @param symbol [Symbol, String]
46
+ # @param locale [Symbol, String, nil]
47
+ # @return [Amount] an instance of the type's registered class
48
+ # @raise [InvalidInput] for too many decimals, misplaced delimiters, a
49
+ # repeated separator, another type's label, or empty input
50
+ # @raise [Registry::UnknownType] for an unregistered symbol
51
+ # @example
52
+ # Amount.parse_ui("1.500,50", :USD, locale: :de) # => USD|1500.50
53
+ def parse_ui(input, symbol, locale: nil)
54
+ UiParser.new(input, symbol, locale).parse
55
+ end
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Amount
4
+ # Concern: the shared type registry and the class-level shortcuts for
5
+ # registering types and default rates.
6
+ #
7
+ # The registry lives on `Amount` itself, never on a subclass, so
8
+ # `GoldAmount.registry` and `Amount.registry` are the same object. Swapping
9
+ # it removes the outgoing registry's generated constructors (`of_usdc`) and
10
+ # installs the incoming one's.
11
+ module Registrable
12
+ def self.included(base)
13
+ base.extend(ClassMethods)
14
+ end
15
+
16
+ # Class-level methods extended onto any class that does
17
+ # `include Registrable`.
18
+ module ClassMethods
19
+ # @return [Amount::Registry]
20
+ # @example Accessing the shared registry
21
+ # Amount.registry.locked?
22
+ # # => false
23
+ def registry
24
+ Amount.instance_variable_get(:@registry) ||
25
+ replace_registry(Registry.new)
26
+ end
27
+
28
+ # @param symbol [Symbol, String]
29
+ # @param opts [Hash]
30
+ # @return [void]
31
+ # @example Registering a type
32
+ # Amount.register :USDC,
33
+ # decimals: 6,
34
+ # display_symbol: "$",
35
+ # display_position: :prefix,
36
+ # ui_decimals: 2
37
+ def register(symbol, **opts)
38
+ registry.register(symbol, **opts)
39
+ end
40
+
41
+ # @param from [Symbol, String]
42
+ # @param to [Symbol, String]
43
+ # @param rate [String, Numeric, BigDecimal]
44
+ # @return [void]
45
+ # @example Registering a directional default rate
46
+ # Amount.register_default_rate :USD, :USDC, "1"
47
+ def register_default_rate(from, to, rate)
48
+ registry.register_default_rate(from, to, rate)
49
+ end
50
+
51
+ # Temporarily swaps the global registry. Intended for tests.
52
+ #
53
+ # @param registry [Amount::Registry]
54
+ # @yield
55
+ # @return [Object]
56
+ # @example Using a temporary registry
57
+ # test_registry = Amount::Registry.new
58
+ # Amount.with_registry(test_registry) do
59
+ # Amount.register :TEST, decimals: 2
60
+ # end
61
+ def with_registry(registry)
62
+ original = Amount.instance_variable_get(:@registry)
63
+ replace_registry(registry)
64
+ yield
65
+ ensure
66
+ replace_registry(original)
67
+ end
68
+
69
+ private
70
+
71
+ def replace_registry(registry)
72
+ current = Amount.instance_variable_get(:@registry)
73
+ current&.remove_generated_methods!
74
+ Amount.instance_variable_set(:@registry, registry)
75
+ registry&.activate_generated_methods!
76
+ registry
77
+ end
78
+ end
79
+ end
80
+ end
@@ -1,12 +1,12 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  class Amount
4
- # Versioned hash serialization. `include Serialization` does both halves:
4
+ # Versioned hash serialization. `include Serializable` does both halves:
5
5
  # the instance side (`#to_h`) is mixed in directly, and the class-level
6
6
  # entry point (`Amount.load`) is auto-extended onto the including class
7
7
  # via the `included` hook below. The compact-string format is the
8
8
  # responsibility of {Amount::Parser}.
9
- module Serialization
9
+ module Serializable
10
10
  VERSION = 1
11
11
 
12
12
  def self.included(base)
@@ -14,7 +14,7 @@ class Amount
14
14
  end
15
15
 
16
16
  # Class-level methods automatically extended onto any class that does
17
- # `include Serialization`.
17
+ # `include Serializable`.
18
18
  module ClassMethods
19
19
  # @param payload [Hash]
20
20
  # @return [Amount]
@@ -51,9 +51,26 @@ class Amount
51
51
  }
52
52
  end
53
53
 
54
+ # The exact compact string: whole units with exactly `decimals` places.
55
+ # Unlike `to_s`, it ignores the display settings and never rounds, so
56
+ # `Amount.parse` reads it back exactly.
57
+ #
54
58
  # @return [String]
59
+ # @example
60
+ # Amount.of_usdc("1.5").as_json # => "USDC|1.500000"
55
61
  def as_json(*)
56
- to_s
62
+ whole, fraction = atomic.abs.divmod(10**decimals)
63
+ number = decimals.zero? ? whole.to_s : "#{whole}.#{fraction.to_s.rjust(decimals, '0')}"
64
+
65
+ "#{symbol}|#{'-' if atomic.negative?}#{number}"
66
+ end
67
+
68
+ # Without ActiveSupport, the `json` library writes an object through
69
+ # `to_s`, so `to_json` goes through {#as_json} explicitly.
70
+ #
71
+ # @return [String]
72
+ def to_json(*args)
73
+ as_json.to_json(*args)
57
74
  end
58
75
  end
59
76
  end
@@ -5,6 +5,19 @@ require "bigdecimal"
5
5
  class Amount
6
6
  # Formats amounts for UI output without changing their type.
7
7
  class Display
8
+ # Rounds to `decimals` places (negative rounds to tens, hundreds, ...),
9
+ # down with `:floor` and up with `:ceil`, like `ui`'s `direction:`.
10
+ # @param value [BigDecimal]
11
+ # @param decimals [Integer]
12
+ # @param direction [Symbol]
13
+ # @return [BigDecimal]
14
+ def self.round(value, decimals, direction)
15
+ factor = BigDecimal(10)**decimals
16
+ scaled = value * factor
17
+ truncated = direction == :ceil ? scaled.ceil : scaled.floor
18
+ truncated / factor
19
+ end
20
+
8
21
  # @param amount [Amount]
9
22
  def initialize(amount)
10
23
  @amount = amount
@@ -25,6 +38,15 @@ class Amount
25
38
  # number. When `nil` (the default), falls back to the display unit's
26
39
  # setting, then the registry entry's setting. An explicit `true` or
27
40
  # `false` overrides both.
41
+ # @param locale [Symbol, String, nil] format the number with this locale's
42
+ # `number.format` delimiter and separator (requires I18n). When `nil`,
43
+ # uses `I18n.locale` if `Amount.localize` is true, else plain output.
44
+ # @param compact [Boolean, Hash] show numbers of one thousand or more in
45
+ # compact notation (`1.5M`, or `1,5 Mio.` with a locale's
46
+ # `number.human.decimal_units` keys). `true` keeps 3 significant digits;
47
+ # `{ precision: 2 }` changes that. Rounds in `direction` and trims
48
+ # trailing zeros. The label and template wrap the compacted number; plural
49
+ # labels agree with the full value. See {Compact}.
28
50
  # @return [String]
29
51
  # @example
30
52
  # Amount.of_usdc("1.50").ui # => "$1.50"
@@ -32,12 +54,45 @@ class Amount
32
54
  # Amount.of_gold("1").ui(unit: :gram) # => "31.10 g"
33
55
  # Amount.of_gold("1").ui(unit: :gram, decorated: false) # => "31.10"
34
56
  # Amount.of_sol("2.5").ui(trim_zeros: true) # => "2.5 SOL"
35
- def ui(unit: nil, direction: :floor, decorated: true, trim_zeros: nil)
36
- if unit
37
- render_display_unit(unit, direction, decorated:, trim_zeros:)
38
- else
39
- render_default(direction, decorated:, trim_zeros:)
40
- end
57
+ # # EUR registered with display_format: "%u%n"; de.yml has
58
+ # # amounts.formats.eur: "%n\u00A0%u"
59
+ # Amount.of_eur("12.5").ui(locale: :en) # => "€12.50"
60
+ # Amount.of_eur("12.5").ui(locale: :de) # => "12,50\u00A0€"
61
+ # Amount.of_usd("1500000").ui(compact: true) # => "$1.5M"
62
+ # Amount.of_tokens(50_000_000).ui(compact: true, decorated: false) # => "50M"
63
+ def ui(unit: nil, direction: :floor, decorated: true, trim_zeros: nil, locale: nil, compact: false)
64
+ locale = Locale.effective(locale)
65
+ precision = Compact.precision(compact)
66
+ spec = @entry.display_unit(unit) if unit
67
+ value = spec ? @amount.decimal * Amount.coerce_decimal(spec[:scale]) : @amount.decimal
68
+ decimals = spec&.dig(:ui_decimals) || @entry.ui_decimals
69
+ rounded = round(value, decimals, direction)
70
+ formatted =
71
+ if precision && Compact.applies?(value)
72
+ Compact.format(value, precision:, direction:, locale:)
73
+ else
74
+ format_number(rounded, decimals, resolve_trim(trim_zeros, spec), locale)
75
+ end
76
+ return formatted unless decorated
77
+
78
+ decorate(formatted, rounded, unit, spec, locale)
79
+ end
80
+
81
+ # The unit label alone, for column headers and chips that render it
82
+ # separately. Follows the same rules as `ui`: translated through I18n only
83
+ # when a locale is given or `Amount.localize` is true, else `display_symbol`
84
+ # (or the display unit's `:symbol`).
85
+ # @param unit [Symbol, nil] display unit
86
+ # @param locale [Symbol, String, nil]
87
+ # @param count [Numeric, String, nil] the number the label agrees with, for
88
+ # plural labels. Without it the `:other` form is used.
89
+ # @return [String]
90
+ # @example
91
+ # Amount.of_searches(3).unit_label(locale: :de) # => "Suchen"
92
+ # Amount.of_searches(1).unit_label(count: 1) # => "search" (hash display_symbol)
93
+ def unit_label(unit: nil, locale: nil, count: nil)
94
+ count = Amount.coerce_decimal(count) unless count.nil?
95
+ label(unit, Locale.effective(locale), nil, count)
41
96
  end
42
97
 
43
98
  # @return [String]
@@ -49,56 +104,42 @@ class Amount
49
104
  # @param unit [Symbol]
50
105
  # @return [BigDecimal]
51
106
  def in_unit(unit)
52
- unit_spec = fetch_display_unit(unit)
107
+ unit_spec = @entry.display_unit(unit)
53
108
  @amount.decimal * Amount.coerce_decimal(unit_spec[:scale])
54
109
  end
55
110
 
56
111
  private
57
112
 
58
- def render_default(direction, decorated:, trim_zeros:)
59
- rounded = round(@amount.decimal, @entry.ui_decimals, direction)
60
- formatted = format_number(rounded, @entry.ui_decimals, resolve_trim(trim_zeros))
61
- return formatted unless decorated
62
-
63
- apply_symbol(formatted, @entry.display_symbol, @entry.display_position)
64
- end
65
-
66
- def render_display_unit(unit, direction, decorated:, trim_zeros:)
67
- spec = fetch_display_unit(unit)
68
- scaled = @amount.decimal * Amount.coerce_decimal(spec[:scale])
69
- decimals = spec[:ui_decimals] || @entry.ui_decimals
70
- rounded = round(scaled, decimals, direction)
71
- formatted = format_number(rounded, decimals, resolve_trim(trim_zeros, spec))
72
- return formatted unless decorated
113
+ # Places the number and its label with the template from
114
+ # {Formattable#display_format}. The label agrees with `count`, the number
115
+ # as displayed. Without a label there is nothing to place, so the number is
116
+ # returned alone.
117
+ def decorate(number, count, unit, spec, locale)
118
+ label = label(unit, locale, spec, count)
119
+ return number if label.nil? || label.empty?
73
120
 
74
- apply_symbol(
75
- formatted,
76
- spec[:symbol] || @entry.display_symbol,
77
- spec[:position] || @entry.display_position
78
- )
121
+ Formattable.fill(@amount.display_format(unit:, locale:), number:, label:)
79
122
  end
80
123
 
81
- def fetch_display_unit(unit)
82
- units = @entry.display_units
83
- unless units
84
- raise Registry::InvalidDisplayUnit, "#{@entry.symbol} has no display_units configured"
85
- end
124
+ def label(unit, locale, spec = nil, count = nil)
125
+ spec ||= @entry.display_unit(unit) if unit
126
+ if spec
127
+ return Locale.plain(spec[:symbol] || @entry.display_symbol, count) unless locale
86
128
 
87
- units.fetch(unit.to_sym) do
88
- raise Registry::InvalidDisplayUnit, "unknown display unit #{unit} for #{@entry.symbol}"
129
+ Locale.unit_label(@entry, unit.to_sym, spec, locale, count)
130
+ else
131
+ locale ? Locale.type_label(@entry, locale, count) : Locale.plain(@entry.display_symbol, count)
89
132
  end
90
133
  end
91
134
 
92
135
  def round(value, decimals, direction)
93
- factor = BigDecimal(10)**decimals
94
- scaled = value * factor
95
- truncated = direction == :ceil ? scaled.ceil : scaled.floor
96
- truncated / factor
136
+ self.class.round(value, decimals, direction)
97
137
  end
98
138
 
99
- def format_number(value, decimals, trim)
139
+ def format_number(value, decimals, trim, locale = nil)
100
140
  str = format("%.#{decimals}f", value)
101
- trim ? str.sub(/(\.\d*?)0+\z/, '\1').chomp('.') : str
141
+ str = str.sub(/(\.\d*?)0+\z/, '\1').chomp('.') if trim
142
+ locale ? Locale.apply(str, locale) : str
102
143
  end
103
144
 
104
145
  def resolve_trim(call_site, spec = nil)
@@ -107,11 +148,5 @@ class Amount
107
148
 
108
149
  @entry.trim_zeros
109
150
  end
110
-
111
- def apply_symbol(str, symbol, position)
112
- return str if symbol.nil? || symbol.empty?
113
-
114
- position == :prefix ? "#{symbol}#{str}" : "#{str} #{symbol}"
115
- end
116
151
  end
117
152
  end