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,102 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Amount
4
+ # Internal: decides the effective locale and reads number formatting from
5
+ # I18n. I18n is used only when it is already loaded; it is never required.
6
+ module Locale
7
+ DEFAULT_DELIMITER = ","
8
+ DEFAULT_SEPARATOR = "."
9
+ MISSING_I18N = "the i18n gem is required for locale-aware output; add it to your Gemfile and require it"
10
+
11
+ module_function
12
+
13
+ # @return [Boolean]
14
+ def i18n_loaded?
15
+ defined?(::I18n) ? true : false
16
+ end
17
+
18
+ # @raise [ArgumentError] when I18n isn't loaded
19
+ def require_i18n!
20
+ raise ArgumentError, MISSING_I18N unless i18n_loaded?
21
+ end
22
+
23
+ # 1. an explicit locale, 2. I18n.locale when Amount.localize, 3. nil.
24
+ # @param explicit [Symbol, String, nil]
25
+ # @return [Symbol, String, nil]
26
+ def effective(explicit = nil)
27
+ unless explicit.nil?
28
+ require_i18n!
29
+ return explicit
30
+ end
31
+ return nil unless Amount.localize?
32
+
33
+ require_i18n!
34
+ ::I18n.locale
35
+ end
36
+
37
+ # @return [Hash{Symbol=>String}] `:delimiter` and `:separator`
38
+ def number_format(locale)
39
+ format = ::I18n.t("number.format", locale:, default: {})
40
+ format = {} unless format.is_a?(Hash)
41
+ {
42
+ delimiter: format[:delimiter] || DEFAULT_DELIMITER,
43
+ separator: format[:separator] || DEFAULT_SEPARATOR
44
+ }
45
+ end
46
+
47
+ # Picks a form from a plural hash without I18n: `:one` when the number
48
+ # equals 1, else `:other`. Strings pass through.
49
+ # @param label [String, Hash, nil]
50
+ # @param count [BigDecimal, nil]
51
+ def plain(label, count)
52
+ return label unless label.is_a?(Hash)
53
+
54
+ count == 1 && label.key?(:one) ? label[:one] : label[:other]
55
+ end
56
+
57
+ # Label of a registered type: its `label_key`, then
58
+ # `amounts.units.<symbol downcased>`, then `display_symbol`.
59
+ # @return [String, nil]
60
+ def type_label(entry, locale, count = nil)
61
+ key = entry.label_key || "amounts.units.#{entry.symbol.to_s.downcase}"
62
+ translate(key, locale, entry.display_symbol, count)
63
+ end
64
+
65
+ # Label of a display unit: the spec's `label_key`, then
66
+ # `amounts.display_units.<symbol downcased>.<unit>`, then the spec's
67
+ # `:symbol`, then the type's label.
68
+ # @return [String, nil]
69
+ def unit_label(entry, unit, spec, locale, count = nil)
70
+ key = spec[:label_key] || "amounts.display_units.#{entry.symbol.to_s.downcase}.#{unit}"
71
+ translate(key, locale, spec[:symbol] || type_label(entry, locale, count), count)
72
+ end
73
+
74
+ # Looks a key up, falling back to `default` so a miss never yields
75
+ # "translation missing". With a count, I18n pluralizes a hash translation
76
+ # or default using the locale's rules; without one, or when the form is
77
+ # missing, the `:other` form is used.
78
+ def translate(key, locale, default, count = nil)
79
+ opts = count.nil? ? {} : { count: whole(count) }
80
+ found = ::I18n.t(key.to_s, locale:, default:, **opts)
81
+ found.is_a?(Hash) ? found[:other] : found
82
+ rescue ::I18n::InvalidPluralizationData => e
83
+ e.entry[:other]
84
+ end
85
+
86
+ # 1.0 -> 1, so custom pluralization rules can match integers.
87
+ def whole(count)
88
+ count.frac.zero? ? count.to_i : count
89
+ end
90
+
91
+ # Rewrites a plain "-1234.50" style number with the locale's characters.
92
+ # @param str [String] output of `format("%.Nf", value)`
93
+ # @return [String]
94
+ def apply(str, locale)
95
+ fmt = number_format(locale)
96
+ sign = str.start_with?("-") ? "-" : ""
97
+ int, frac = str.delete_prefix("-").split(".", 2)
98
+ int = int.reverse.scan(/\d{1,3}/).join(fmt[:delimiter].reverse).reverse
99
+ "#{sign}#{int}#{frac ? "#{fmt[:separator]}#{frac}" : ''}"
100
+ end
101
+ end
102
+ end
@@ -2,7 +2,6 @@
2
2
 
3
3
  require "bigdecimal"
4
4
  require "thread"
5
- require_relative "registry/generated_constructors"
6
5
 
7
6
  class Amount
8
7
  # Stores registered amount types and default directional conversion rates.
@@ -25,19 +24,33 @@ class Amount
25
24
  class RegistryLocked < StandardError; end
26
25
  class AlreadyRegistered < StandardError; end
27
26
  class InvalidDisplayUnit < StandardError; end
27
+ class InvalidDisplaySymbol < StandardError; end
28
28
 
29
29
  Entry = Struct.new(
30
30
  :symbol,
31
31
  :decimals,
32
32
  :display_symbol,
33
+ :label_key,
33
34
  :display_position,
35
+ :display_format,
34
36
  :ui_decimals,
35
37
  :display_units,
36
38
  :default_display,
37
39
  :amount_class,
38
40
  :trim_zeros,
39
41
  keyword_init: true
40
- )
42
+ ) do
43
+ # @param unit [Symbol, String]
44
+ # @return [Hash] the display unit's spec
45
+ # @raise [InvalidDisplayUnit] when the type has no such display unit
46
+ def display_unit(unit)
47
+ raise InvalidDisplayUnit, "#{symbol} has no display_units configured" unless display_units
48
+
49
+ display_units.fetch(unit.to_sym) do
50
+ raise InvalidDisplayUnit, "unknown display unit #{unit} for #{symbol}"
51
+ end
52
+ end
53
+ end
41
54
 
42
55
  def initialize
43
56
  @entries = {}
@@ -57,8 +70,19 @@ class Amount
57
70
  #
58
71
  # @param symbol [Symbol, String] registered type identifier
59
72
  # @param decimals [Integer] number of storage decimals
60
- # @param display_symbol [String] symbol used by UI helpers
61
- # @param display_position [Symbol] either `:prefix` or `:suffix`
73
+ # @param display_symbol [String, Hash] symbol used by UI helpers. A hash
74
+ # (`{ one: "search", other: "searches" }`) gives plural forms and must
75
+ # have `:other`
76
+ # @param label_key [String, Symbol, nil] I18n key for the unit label, used
77
+ # when localizing. Defaults to `amounts.units.<symbol downcased>`;
78
+ # a missing translation falls back to `display_symbol`
79
+ # @param display_position [Symbol, nil] `:prefix` (`"$1.50"`) or `:suffix`
80
+ # (`"1.50 SOL"`, the default). Shorthand for the templates `"%u%n"` and
81
+ # `"%n %u"`; can't be combined with `display_format`
82
+ # @param display_format [String, nil] template for decorated `ui` output,
83
+ # where `%n` is the formatted number (sign included) and `%u` the label,
84
+ # e.g. `"%n\u00A0%u"`. Used exactly as given. When localizing,
85
+ # `amounts.formats.<symbol downcased>` overrides it
62
86
  # @param ui_decimals [Integer] decimals displayed by default UI formatting
63
87
  # @param display_units [Hash, nil] optional display-only scaling definitions
64
88
  # @param default_display [Symbol, nil] optional default display unit key
@@ -68,14 +92,16 @@ class Amount
68
92
  # @raise [AlreadyRegistered] if the symbol is already registered or the
69
93
  # generated constructor would collide with an existing method
70
94
  # @raise [RegistryLocked] if the registry has been locked
95
+ # @raise [ArgumentError] if both `display_format` and `display_position`
96
+ # are given, or `display_format` is not a String containing `%n`
71
97
  # @example
72
98
  # Amount.register :USDC,
73
99
  # decimals: 6,
74
100
  # display_symbol: "$",
75
101
  # display_position: :prefix,
76
102
  # ui_decimals: 2
77
- def register(symbol, decimals:, display_symbol: symbol.to_s, display_position: :suffix,
78
- ui_decimals: decimals, display_units: nil, default_display: nil,
103
+ def register(symbol, decimals:, display_symbol: symbol.to_s, label_key: nil, display_position: nil,
104
+ display_format: nil, ui_decimals: decimals, display_units: nil, default_display: nil,
79
105
  trim_zeros: false, class: nil)
80
106
  raise ArgumentError, "symbol must not be blank" if symbol.nil? || symbol.to_s.empty?
81
107
 
@@ -85,13 +111,17 @@ class Amount
85
111
  ensure_unlocked!
86
112
  raise AlreadyRegistered, "#{symbol} already registered" if @entries.key?(symbol)
87
113
 
114
+ validate_display_symbol!(:display_symbol, display_symbol, InvalidDisplaySymbol)
115
+ validate_display_format!(display_format, display_position) if display_format
88
116
  validate_display_units!(display_units, default_display) if display_units
89
117
 
90
118
  entry = Entry.new(
91
119
  symbol:,
92
120
  decimals:,
93
121
  display_symbol:,
94
- display_position:,
122
+ label_key: label_key&.to_s,
123
+ display_position: display_format ? nil : (display_position || :suffix),
124
+ display_format: display_format || Formattable.template_for(display_position),
95
125
  ui_decimals:,
96
126
  display_units:,
97
127
  default_display:,
@@ -230,6 +260,13 @@ class Amount
230
260
  raise RegistryLocked, "registry is locked" if @locked
231
261
  end
232
262
 
263
+ def validate_display_format!(format, position)
264
+ raise ArgumentError, "pass display_format or display_position, not both" if position
265
+ return if Formattable.valid_template?(format)
266
+
267
+ raise ArgumentError, "display_format must be a String containing %n"
268
+ end
269
+
233
270
  def validate_display_units!(units, default)
234
271
  unless units.is_a?(Hash) && !units.empty?
235
272
  raise InvalidDisplayUnit, "display_units must be a non-empty hash"
@@ -243,7 +280,32 @@ class Amount
243
280
  unless spec.is_a?(Hash) && spec.key?(:scale)
244
281
  raise InvalidDisplayUnit, "display_unit #{key} must have :scale"
245
282
  end
283
+
284
+ validate_unit_format!(key, spec) if spec.key?(:format)
285
+ validate_display_symbol!("display_unit #{key} :symbol", spec[:symbol], InvalidDisplayUnit) if spec[:symbol]
286
+ end
287
+ end
288
+
289
+ def validate_unit_format!(key, spec)
290
+ if spec.key?(:position)
291
+ raise InvalidDisplayUnit, "display_unit #{key} takes :format or :position, not both"
246
292
  end
293
+ return if Formattable.valid_template?(spec[:format])
294
+
295
+ raise InvalidDisplayUnit, "display_unit #{key} :format must be a String containing %n"
296
+ end
297
+
298
+ def validate_display_symbol!(name, value, error)
299
+ return unless value.is_a?(Hash)
300
+
301
+ unless value.key?(:other)
302
+ raise error, "#{name} hash must have an :other key (got #{value.keys.inspect})"
303
+ end
304
+
305
+ bad = value.reject { |k, v| k.is_a?(Symbol) && v.is_a?(String) }
306
+ return if bad.empty?
307
+
308
+ raise error, "#{name} hash must map Symbol plural keys to String labels (got #{bad.inspect})"
247
309
  end
248
310
  end
249
311
  end
@@ -0,0 +1,109 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Amount
4
+ # Internal: parses the text a person types into a form field, optionally in
5
+ # a locale's number format. Exact: never rounds, never goes through Float.
6
+ class UiParser
7
+ # @param input [#to_s]
8
+ # @param symbol [Symbol, String]
9
+ # @param locale [Symbol, String, nil]
10
+ def initialize(input, symbol, locale)
11
+ @input = input
12
+ @entry = Amount.registry.lookup(symbol)
13
+ @locale = Locale.effective(locale)
14
+ format = @locale ? Locale.number_format(@locale) : { delimiter: "", separator: "." }
15
+ @delimiter = format[:delimiter].to_s
16
+ @separator = format[:separator].to_s
17
+ end
18
+
19
+ # @return [Amount]
20
+ def parse
21
+ text = strip(@input.to_s)
22
+ fail_with("is empty") if text.empty?
23
+ original = text
24
+
25
+ sign, text = take_sign(text)
26
+ @signed = text != original
27
+ unlabeled = strip_label(text)
28
+ # "$-1.50": a sign may follow a prefix label, but not as a second sign
29
+ sign, unlabeled = take_sign(unlabeled) if sign.empty? && unlabeled != text && !@signed
30
+ text = unlabeled
31
+ value = atomic(text)
32
+ Amount.new(sign.empty? ? value : -value, @entry.symbol)
33
+ end
34
+
35
+ private
36
+
37
+ def fail_with(reason)
38
+ raise InvalidInput, "cannot parse #{@input.inspect} as #{@entry.symbol}: #{reason}"
39
+ end
40
+
41
+ def strip(str)
42
+ str.gsub(/\A[[:space:]]+|[[:space:]]+\z/, "")
43
+ end
44
+
45
+ # @return [Array(String, String)] "-" or "" (a "+" is dropped), and the rest
46
+ def take_sign(text)
47
+ match = text.match(/\A([+-])[[:space:]]*(.*)\z/m)
48
+ return ["", text] unless match
49
+
50
+ [match[1] == "-" ? "-" : "", match[2]]
51
+ end
52
+
53
+ # Removes one label (the longest match) from either end.
54
+ def strip_label(text)
55
+ labels.each do |label|
56
+ if text.start_with?(label)
57
+ return strip(text.delete_prefix(label))
58
+ elsif text.end_with?(label)
59
+ return strip(text.delete_suffix(label))
60
+ end
61
+ end
62
+ text
63
+ end
64
+
65
+ # Every form of the type's label: `display_symbol` (and its plural
66
+ # forms), plus the locale's translation when localizing.
67
+ def labels
68
+ found = forms(@entry.display_symbol)
69
+ found += forms(translation) if @locale
70
+ found.map(&:to_s).reject(&:empty?).uniq.sort_by { |label| -label.length }
71
+ end
72
+
73
+ def translation
74
+ key = @entry.label_key || "amounts.units.#{@entry.symbol.to_s.downcase}"
75
+ ::I18n.t(key.to_s, locale: @locale, default: nil)
76
+ end
77
+
78
+ def forms(label)
79
+ case label
80
+ when Hash then label.values.grep(String)
81
+ when String then [label]
82
+ else []
83
+ end
84
+ end
85
+
86
+ # @return [Integer] atomic units, unsigned
87
+ def atomic(text)
88
+ whole, fraction, extra = text.split(@separator, -1)
89
+ fail_with("a decimal separator is used twice") if extra
90
+ fail_with("is not a number") unless whole&.match?(whole_pattern)
91
+ fraction ||= ""
92
+ fail_with("is not a number") if text.include?(@separator) && fraction.empty?
93
+ fail_with("is not a number") unless fraction.match?(/\A\d*\z/)
94
+ if fraction.length > @entry.decimals
95
+ fail_with("has more than #{@entry.decimals} decimal places")
96
+ end
97
+
98
+ digits = whole.gsub(/\D/, "") + fraction.ljust(@entry.decimals, "0")
99
+ digits.to_i
100
+ end
101
+
102
+ def whole_pattern
103
+ return /\A\d+\z/ if @delimiter.empty?
104
+
105
+ glue = @delimiter.match?(/\A[[:space:]]+\z/) ? "[[:space:]]" : Regexp.escape(@delimiter)
106
+ /\A(?:\d+|\d{1,3}(?:#{glue}\d{3})+)\z/
107
+ end
108
+ end
109
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  class Amount
4
- VERSION = "0.0.8"
4
+ VERSION = "0.2.0"
5
5
  end
data/lib/amount.rb CHANGED
@@ -3,15 +3,31 @@
3
3
  require "bigdecimal"
4
4
  require "forwardable"
5
5
 
6
+ # Every core file loads from here, in dependency order; core files don't
7
+ # require each other. The optional adapters (amount/active_record,
8
+ # amount/rspec) are separate entry points that load their own files.
6
9
  require_relative "amount/version"
7
10
  require_relative "amount/registry"
11
+ require_relative "amount/registry/generated_constructors"
12
+ require_relative "amount/locale"
13
+ require_relative "amount/compact"
8
14
  require_relative "amount/display"
9
15
  require_relative "amount/parser"
10
- require_relative "amount/arithmetic"
11
- require_relative "amount/allocation"
12
- require_relative "amount/comparison"
13
- require_relative "amount/conversion"
14
- require_relative "amount/serialization"
16
+ require_relative "amount/ui_parser"
17
+
18
+ # Concerns: modules mixed into Amount. Files live in amount/concerns/, but the
19
+ # constants are Amount::<Name> (the folder is not a namespace).
20
+ require_relative "amount/concerns/registrable"
21
+ require_relative "amount/concerns/localizable"
22
+ require_relative "amount/concerns/parsable"
23
+ require_relative "amount/concerns/constructible"
24
+ require_relative "amount/concerns/coercible"
25
+ require_relative "amount/concerns/calculable"
26
+ require_relative "amount/concerns/allocatable"
27
+ require_relative "amount/concerns/orderable"
28
+ require_relative "amount/concerns/convertible"
29
+ require_relative "amount/concerns/serializable"
30
+ require_relative "amount/concerns/formattable"
15
31
 
16
32
  # Represents a precise quantity of a registered fungible type.
17
33
  #
@@ -20,12 +36,26 @@ require_relative "amount/serialization"
20
36
  # strings or decimals, while integer inputs are treated as atomic counts unless
21
37
  # `from:` overrides inference.
22
38
  #
23
- # Behavior is composed from a set of focused mixins:
24
- # - {Arithmetic} — `+`, `-`, `*`, `/`, `abs`, `-@`
25
- # - {Comparison} — `<=>`, `==`, `eql?`, `hash`, `same_type?`, sign predicates
26
- # - {Conversion} — `to(:SYMBOL, rate:)`
27
- # - {Allocation} — `split(n)`, `allocate(weights)`
28
- # - {Serialization} — `to_h`
39
+ # This class holds only an amount's identity: its atomic value, its symbol and
40
+ # registry entry, and the decimal view of the value. Everything else comes
41
+ # from concerns:
42
+ # - {Registrable} — `Amount.registry`, `register`, `register_default_rate`,
43
+ # `with_registry`
44
+ # - {Localizable} — `Amount.localize`
45
+ # - {Parsable} — `Amount.parse`, `Amount.parse_ui`
46
+ # - {Constructible} — input inference, `Amount.new` dispatch to a registered
47
+ # subclass, `build`
48
+ # - {Coercible} — `Amount.coerce_decimal`, cross-type operand coercion
49
+ # - {Calculable} — `+`, `-`, `*`, `/`, `abs`, `-@`
50
+ # - {Orderable} — `<=>`, `==`, `eql?`, `hash`, `same_type?`, sign predicates
51
+ # - {Convertible} — `to(:SYMBOL, rate:)`
52
+ # - {Allocatable} — `split(n)`, `allocate(weights)`
53
+ # - {Serializable} — `to_h`, `as_json`, `Amount.load`
54
+ # - {Formattable} — `display_format(unit:, locale:)`, where the number and
55
+ # unit go
56
+ #
57
+ # New behavior belongs in a concern, not in this class. See
58
+ # `.claude/rules/concerns.md` for the shape a concern takes.
29
59
  #
30
60
  # @example Constructing from a UI value
31
61
  # Amount.register :USDC, decimals: 6
@@ -37,11 +67,17 @@ require_relative "amount/serialization"
37
67
  # Amount.of_usdc(1_500_000, from: :atomic).decimal.to_s("F")
38
68
  # # => "1.5"
39
69
  class Amount
40
- include Arithmetic
41
- include Allocation
42
- include Comparison
43
- include Conversion
44
- include Serialization
70
+ include Registrable
71
+ include Localizable
72
+ include Parsable
73
+ include Constructible
74
+ include Coercible
75
+ include Calculable
76
+ include Allocatable
77
+ include Orderable
78
+ include Convertible
79
+ include Serializable
80
+ include Formattable
45
81
 
46
82
  extend Forwardable
47
83
 
@@ -50,128 +86,11 @@ class Amount
50
86
  class InvalidInput < Error; end
51
87
  class UnregisteredType < Error; end
52
88
 
53
- class << self
54
- # @return [Amount::Registry]
55
- # @example Accessing the shared registry
56
- # Amount.registry.locked?
57
- # # => false
58
- def registry
59
- Amount.instance_variable_get(:@registry) ||
60
- replace_registry(Registry.new)
61
- end
62
-
63
- # @param symbol [Symbol, String]
64
- # @param opts [Hash]
65
- # @return [void]
66
- # @example Registering a type
67
- # Amount.register :USDC,
68
- # decimals: 6,
69
- # display_symbol: "$",
70
- # display_position: :prefix,
71
- # ui_decimals: 2
72
- def register(symbol, **opts)
73
- registry.register(symbol, **opts)
74
- end
75
-
76
- # @param from [Symbol, String]
77
- # @param to [Symbol, String]
78
- # @param rate [String, Numeric, BigDecimal]
79
- # @return [void]
80
- # @example Registering a directional default rate
81
- # Amount.register_default_rate :USD, :USDC, "1"
82
- def register_default_rate(from, to, rate)
83
- registry.register_default_rate(from, to, rate)
84
- end
85
-
86
- # Parses the compact client-facing string representation.
87
- #
88
- # Accepts either the default form `SYMBOL|amount` or the explicit versioned
89
- # form `v1:SYMBOL|amount`.
90
- #
91
- # @param str [String]
92
- # @return [Amount]
93
- # @raise [InvalidInput]
94
- # @example Parsing the default compact format
95
- # Amount.parse("USDC|1.50")
96
- #
97
- # @example Parsing the explicit versioned compact format
98
- # Amount.parse("v1:USDC|1.50")
99
- def parse(str)
100
- Parser.new(str).parse
101
- end
102
-
103
- # When called as `Amount.new` for a symbol whose registry entry binds a
104
- # custom class, dispatch the construction to that class instead of raising.
105
- # Direct calls to a subclass (`GoldAmount.new(...)`) still go through the
106
- # default `Class.new` path. Calls that target the wrong subclass continue
107
- # to raise from `#initialize`.
108
- #
109
- # @param value [Integer, String, Float, BigDecimal, Rational]
110
- # @param symbol [Symbol, String]
111
- # @param from [Symbol, nil]
112
- # @return [Amount]
113
- def new(value, symbol, from: nil)
114
- if equal?(::Amount)
115
- entry_class = registry.lookup(symbol.to_sym).amount_class
116
- return entry_class.new(value, symbol, from:) if entry_class && entry_class != ::Amount
117
- end
118
- super
119
- end
120
-
121
- # Coerces a numeric input to BigDecimal in a way that preserves Rational
122
- # values. `BigDecimal(value.to_s)` raises `ArgumentError` for Rational
123
- # because `Rational#to_s` produces strings like `"3/2"`. This helper is
124
- # the single place every call site should use to convert a scalar / rate /
125
- # display-unit scale into a BigDecimal.
126
- #
127
- # @param value [Numeric, BigDecimal, Rational, String]
128
- # @return [BigDecimal]
129
- def coerce_decimal(value)
130
- case value
131
- when BigDecimal then value
132
- when Rational then BigDecimal(value, Float::DIG + 4)
133
- else BigDecimal(value.to_s)
134
- end
135
- end
136
-
137
- # Temporarily swaps the global registry. Intended for tests.
138
- #
139
- # @param registry [Amount::Registry]
140
- # @yield
141
- # @return [Object]
142
- # @example Using a temporary registry
143
- # test_registry = Amount::Registry.new
144
- # Amount.with_registry(test_registry) do
145
- # Amount.register :TEST, decimals: 2
146
- # end
147
- def with_registry(registry)
148
- original = Amount.instance_variable_get(:@registry)
149
- replace_registry(registry)
150
- yield
151
- ensure
152
- replace_registry(original)
153
- end
154
-
155
- private
156
-
157
- def replace_registry(registry)
158
- current = Amount.instance_variable_get(:@registry)
159
- current&.remove_generated_methods!
160
- Amount.instance_variable_set(:@registry, registry)
161
- registry&.activate_generated_methods!
162
- registry
163
- end
164
- end
165
-
166
89
  attr_reader :atomic, :symbol, :display
167
90
 
168
91
  # Creates an amount for a registered symbol.
169
92
  #
170
- # Input inference rules:
171
- # - `Integer` => atomic units
172
- # - `String` => UI decimal value
173
- # - `Float`, `BigDecimal`, `Rational` => UI decimal value
174
- # - `from:` overrides inference explicitly
93
+ # See {Constructible} for how `value` is read.
175
94
  #
176
95
  # @param value [Integer, String, Float, BigDecimal, Rational]
177
96
  # @param symbol [Symbol, String] registered type identifier
@@ -188,12 +107,7 @@ class Amount
188
107
  def initialize(value, symbol, from: nil)
189
108
  @symbol = symbol.to_sym
190
109
  @entry = self.class.registry.lookup(@symbol)
191
-
192
- expected = @entry.amount_class
193
- if expected && expected != Amount && self.class != Amount && !instance_of?(expected)
194
- raise InvalidInput, "use #{expected}.new for #{@symbol}"
195
- end
196
-
110
+ ensure_registered_class!
197
111
  @atomic = infer_value(from, value)
198
112
  @display = Display.new(self)
199
113
  end
@@ -222,7 +136,7 @@ class Amount
222
136
  BigDecimal(@atomic) / (BigDecimal(10)**decimals)
223
137
  end
224
138
 
225
- def_delegators :display, :formatted, :ui, :to_s, :in_unit
139
+ def_delegators :display, :formatted, :ui, :unit_label, :to_s, :in_unit
226
140
 
227
141
  # @return [String]
228
142
  # @example Console-friendly inspection
@@ -231,62 +145,4 @@ class Amount
231
145
  def inspect
232
146
  "#<#{self.class} #{symbol} #{ui}>"
233
147
  end
234
-
235
- private
236
-
237
- # Builds a same-symbol amount in the receiver's class. Used by every
238
- # operator that returns an Amount so subclass identity propagates.
239
- def build(atomic_value)
240
- self.class.new(atomic_value, symbol, from: :atomic)
241
- end
242
-
243
- def ensure_same_type!(other)
244
- return if same_type?(other)
245
-
246
- raise TypeMismatch, "type mismatch: #{symbol} vs #{other.is_a?(Amount) ? other.symbol : other.class}"
247
- end
248
-
249
- def coerce_other_to_self_type(other)
250
- return other if same_type?(other)
251
- return unless other.is_a?(Amount)
252
-
253
- other.to(symbol)
254
- rescue Registry::NoDefaultRate
255
- nil
256
- end
257
-
258
- def coerce_other_to_self_type!(other)
259
- coerce_other_to_self_type(other) || raise(
260
- TypeMismatch,
261
- "type mismatch: #{symbol} vs #{other.is_a?(Amount) ? other.symbol : other.class}"
262
- )
263
- end
264
-
265
- def infer_value(from, value)
266
- case from || infer_type(value)
267
- when :atomic then value.to_i
268
- when :ui then ui_to_atomic(value)
269
- when :float then ui_to_atomic(value.is_a?(Rational) ? value : value.to_s)
270
- else
271
- raise InvalidInput, "unknown amount format: #{value.inspect}"
272
- end
273
- end
274
-
275
- def infer_type(value)
276
- case value
277
- when Integer then :atomic
278
- when String then :ui
279
- when Float, BigDecimal, Rational then :float
280
- else
281
- raise InvalidInput, "cannot infer type for #{value.class}"
282
- end
283
- end
284
-
285
- def ui_to_atomic(value)
286
- return (value * (10**decimals)).to_i if value.is_a?(Rational)
287
-
288
- (BigDecimal(value.to_s) * (BigDecimal(10)**decimals)).to_i
289
- rescue ArgumentError
290
- raise InvalidInput, "cannot parse #{value.inspect} as #{symbol}"
291
- end
292
148
  end