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
@@ -41,7 +41,7 @@ class Amount
41
41
  def validate_amount_instance(record, attribute, value)
42
42
  return if value.is_a?(::Amount)
43
43
 
44
- record.errors.add(attribute, "must be an Amount")
44
+ record.errors.add(attribute, :amount_type)
45
45
  end
46
46
 
47
47
  def validate_symbol(record, attribute, value)
@@ -49,7 +49,7 @@ class Amount
49
49
  return unless expected_symbol
50
50
  return if value.symbol == expected_symbol
51
51
 
52
- record.errors.add(attribute, "must have symbol #{expected_symbol}")
52
+ record.errors.add(attribute, :amount_symbol, expected: expected_symbol)
53
53
  end
54
54
 
55
55
  def validate_comparators(record, attribute, value)
@@ -61,7 +61,7 @@ class Amount
61
61
 
62
62
  compare_amounts(record, attribute, value, operator, other, option_name)
63
63
  rescue ::Amount::Error, ArgumentError => error
64
- record.errors.add(attribute, "has invalid #{option_name} constraint: #{error.message}")
64
+ record.errors.add(attribute, :amount_invalid_constraint, option: option_name, message: error.message)
65
65
  end
66
66
  end
67
67
 
@@ -78,28 +78,19 @@ class Amount
78
78
  def compare_amounts(record, attribute, value, operator, other, option_name)
79
79
  comparison = value <=> other
80
80
  if comparison.nil?
81
- record.errors.add(attribute, "cannot compare #{value.symbol} to #{other.symbol} for #{option_name}")
81
+ record.errors.add(attribute, :amount_incomparable,
82
+ symbol: value.symbol, other_symbol: other.symbol, option: option_name)
82
83
  return
83
84
  end
84
85
 
85
86
  return if comparison.public_send(operator, 0)
86
87
 
87
- record.errors.add(attribute, failure_message(option_name, other))
88
+ record.errors.add(attribute, failure_key(option_name), count: other.to_s)
88
89
  end
89
90
 
90
- def failure_message(option_name, other)
91
- case option_name
92
- when :greater_than
93
- "must be greater than #{other}"
94
- when :greater_than_or_equal_to
95
- "must be greater than or equal to #{other}"
96
- when :less_than
97
- "must be less than #{other}"
98
- when :less_than_or_equal_to
99
- "must be less than or equal to #{other}"
100
- else
101
- "is invalid"
102
- end
91
+ # Rails' own keys, so apps that translate them get these for free.
92
+ def failure_key(option_name)
93
+ COMPARATORS.key?(option_name) ? option_name : :invalid
103
94
  end
104
95
 
105
96
  def fetch_definition(record, attribute)
@@ -35,17 +35,23 @@ class Amount
35
35
  end
36
36
 
37
37
  def write(record, value)
38
- if value.nil?
39
- record.write_attribute(atomic_column, nil)
40
- record.write_attribute(symbol_column, nil) unless fixed_symbol?
41
- return nil
42
- end
43
-
44
- record.write_attribute(atomic_column, value.atomic.to_s)
45
- record.write_attribute(symbol_column, value.symbol.to_s) unless fixed_symbol?
38
+ column_values(value).each { |column, column_value| record.write_attribute(column, column_value) }
46
39
  value
47
40
  end
48
41
 
42
+ # The component column values that store `value`, an Amount or `nil`.
43
+ # Every component column is present, so rows built from it share keys.
44
+ #
45
+ # @param value [Amount, nil]
46
+ # @return [Hash{String => Integer, String, nil}]
47
+ def column_values(value)
48
+ # The Integer itself, not its string: Rails 8.1 cuts a String cast to an
49
+ # integer column to 16 bytes, which silently truncates large values.
50
+ values = { atomic_column => value&.atomic }
51
+ values[symbol_column] = value&.symbol&.to_s unless fixed_symbol?
52
+ values
53
+ end
54
+
49
55
  def build_from_values(values)
50
56
  type.deserialize(values[atomic_column], fixed_symbol? ? symbol : values[symbol_column])
51
57
  end
@@ -0,0 +1,127 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Amount
4
+ module ActiveRecord
5
+ # Aggregates `has_amount` attributes in SQL and returns Amounts.
6
+ #
7
+ # Each method runs one query in the scope of the relation it is called
8
+ # on, so `where` and `group` apply. Ungrouped, it returns one Amount (or
9
+ # `nil`); grouped, it returns a Hash keyed like Rails' `group(...).sum`,
10
+ # by the group's value, or by an array of values for several groups.
11
+ # Group by a column or SQL expression; grouping by an association name
12
+ # raises `ArgumentError` (group by its foreign key instead).
13
+ #
14
+ # Amounts of different symbols never combine: a multi-symbol attribute
15
+ # with more than one symbol in scope, or in one group, raises
16
+ # {Amount::TypeMismatch}. Group by its symbol column for one Amount per
17
+ # symbol.
18
+ #
19
+ # @example
20
+ # UsageRecord.sum_amount(:cost) # => #<Amount USDP ...>
21
+ # UsageRecord.group(:kind).sum_amount(:cost) # => { "search" => #<Amount USDP ...> }
22
+ # UsageRecord.group(:quantity_symbol).sum_amount(:quantity)
23
+ module Calculations
24
+ # A fixed-symbol sum over no rows is zero; a multi-symbol one is `nil`.
25
+ #
26
+ # @param name [Symbol, String] a `has_amount` attribute
27
+ # @return [Amount, Hash, nil]
28
+ # @raise [Amount::TypeMismatch] when amounts of more than one symbol meet
29
+ def sum_amount(name)
30
+ # SQL's SUM is NULL over no rows, and `none` runs no query at all;
31
+ # Rails' `sum` is zero for both. `deserialize(0)` is that zero for a
32
+ # fixed symbol and `nil` for a multi-symbol attribute.
33
+ zero = amount_attribute_definitions.fetch(name.to_sym).type.deserialize(0)
34
+ aggregate_amount(name, :sum) { |sum| sum || zero } || zero
35
+ end
36
+
37
+ # @param name [Symbol, String] a `has_amount` attribute
38
+ # @return [Amount, Hash, nil] `nil` over no rows
39
+ # @raise [Amount::TypeMismatch] when amounts of more than one symbol meet
40
+ def minimum_amount(name)
41
+ aggregate_amount(name, :minimum) { |minimum| minimum }
42
+ end
43
+
44
+ # @param name [Symbol, String] a `has_amount` attribute
45
+ # @return [Amount, Hash, nil] `nil` over no rows
46
+ # @raise [Amount::TypeMismatch] when amounts of more than one symbol meet
47
+ def maximum_amount(name)
48
+ aggregate_amount(name, :maximum) { |maximum| maximum }
49
+ end
50
+
51
+ # The sum divided by the number of amounts, truncated toward zero to a
52
+ # whole atomic unit, as `Amount#/` does. The sum and the count come from
53
+ # the same query.
54
+ #
55
+ # @param name [Symbol, String] a `has_amount` attribute
56
+ # @return [Amount, Hash, nil] `nil` over no rows
57
+ # @raise [Amount::TypeMismatch] when amounts of more than one symbol meet
58
+ def average_amount(name)
59
+ aggregate_amount(name, :sum, :count) { |sum, count| sum / count unless count.zero? }
60
+ end
61
+
62
+ private
63
+
64
+ # Plucks the caller's groups, the symbol and the aggregates as
65
+ # `[*groups, symbol, atomic, *rest]`, then yields each group's first
66
+ # aggregate as an Amount, with the rest as they came.
67
+ def aggregate_amount(name, *operations)
68
+ definition = amount_attribute_definitions.fetch(name.to_sym)
69
+ groups = amount_group_values
70
+ atomic = arel_table[definition.atomic_column]
71
+
72
+ rows = amount_aggregate_scope(definition)
73
+ .pluck(*groups, amount_symbol_select(definition),
74
+ *operations.map { |operation| atomic.public_send(operation) })
75
+
76
+ results = rows.group_by { |row| amount_group_key(row.first(groups.size)) }
77
+ .transform_values do |group_rows|
78
+ yield(*amount_group_values_of(definition, group_rows.map { |row| row.drop(groups.size) }))
79
+ end
80
+
81
+ groups.empty? ? results[[]] : results
82
+ end
83
+
84
+ # The caller passed these to `group`, which takes raw SQL; `pluck` takes
85
+ # a SQL string only wrapped in `Arel.sql`.
86
+ def amount_group_values
87
+ all.group_values.map do |group|
88
+ reflection = group.respond_to?(:to_sym) && _reflect_on_association(group)
89
+ if reflection
90
+ raise ArgumentError,
91
+ "group by #{reflection.foreign_key}, not the #{group} association, to aggregate amounts"
92
+ end
93
+
94
+ group.is_a?(String) ? ::Arel.sql(group) : group
95
+ end
96
+ end
97
+
98
+ # A multi-symbol attribute is grouped by its symbol too, so each row is
99
+ # one symbol's aggregate. Rows without an amount are left out.
100
+ def amount_aggregate_scope(definition)
101
+ return all if definition.fixed_symbol?
102
+
103
+ where.not(definition.symbol_column => nil).group(definition.symbol_column)
104
+ end
105
+
106
+ def amount_symbol_select(definition)
107
+ return ::Arel::Nodes.build_quoted(definition.symbol.to_s) if definition.fixed_symbol?
108
+
109
+ arel_table[definition.symbol_column]
110
+ end
111
+
112
+ def amount_group_key(values)
113
+ values.size == 1 ? values.first : values
114
+ end
115
+
116
+ def amount_group_values_of(definition, rows)
117
+ unless rows.size == 1
118
+ raise ::Amount::TypeMismatch,
119
+ "#{definition.name} has more than one symbol in scope: #{rows.map(&:first).join(', ')}"
120
+ end
121
+
122
+ symbol, atomic, *rest = rows.first
123
+ [definition.type.deserialize(atomic, symbol), *rest]
124
+ end
125
+ end
126
+ end
127
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Amount
4
+ module ActiveRecord
5
+ # Change hashes with each `has_amount` attribute by its name, as
6
+ # `[before, after]` Amounts, in place of its component columns.
7
+ # `has_amount` includes it into the model that declares an amount.
8
+ #
9
+ # Rails' own `changes` and `saved_changes` are left as they are, keyed
10
+ # by column, for the code and gems that read them that way.
11
+ #
12
+ # @example
13
+ # subscription.update!(owed: Amount.of_usd("10.06"))
14
+ # subscription.saved_changes # => { "owed_atomic" => [0, 1006], ... }
15
+ # subscription.saved_amount_changes # => { "owed" => [#<Amount USD $0.00>, #<Amount USD $10.06>], ... }
16
+ module Dirty
17
+ # Like `changes`: the changes not yet saved.
18
+ #
19
+ # @return [ActiveSupport::HashWithIndifferentAccess]
20
+ def amount_changes
21
+ amounts_in_place_of_column_changes(changes) { |definition| definition.change(self) }
22
+ end
23
+
24
+ # Like `saved_changes`: the changes the last save made.
25
+ #
26
+ # @return [ActiveSupport::HashWithIndifferentAccess]
27
+ def saved_amount_changes
28
+ amounts_in_place_of_column_changes(saved_changes) { |definition| definition.saved_change(self) }
29
+ end
30
+
31
+ private
32
+
33
+ def amounts_in_place_of_column_changes(column_changes)
34
+ self.class.amount_attribute_definitions.each_value do |definition|
35
+ change = yield(definition)
36
+ definition.component_columns.each { |column| column_changes.delete(column) }
37
+ column_changes[definition.name.to_s] = change if change
38
+ end
39
+ column_changes
40
+ end
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,7 @@
1
+ en:
2
+ errors:
3
+ messages:
4
+ amount_type: "must be an Amount"
5
+ amount_symbol: "must have symbol %{expected}"
6
+ amount_invalid_constraint: "has invalid %{option} constraint: %{message}"
7
+ amount_incomparable: "cannot compare %{symbol} to %{other_symbol} for %{option}"
@@ -4,9 +4,20 @@ class Amount
4
4
  module ActiveRecord
5
5
  # Provides `has_amount` for ActiveRecord models.
6
6
  module Model
7
+ # The definitions are a class attribute, so a subclass (STI included)
8
+ # sees its parent's amounts. `has_amount` assigns a new Hash rather than
9
+ # changing the inherited one, so a subclass's amounts stay its own.
10
+ def self.extended(base)
11
+ base.class_attribute :amount_attribute_definitions, instance_accessor: false, default: {}.freeze
12
+ end
13
+
7
14
  def has_amount(name, symbol: nil)
15
+ # Into this model only; a repeat `include` does nothing, and
16
+ # subclasses inherit them.
17
+ include Serialization, Dirty
18
+
8
19
  definition = AttributeDefinition.new(name, symbol:)
9
- amount_attribute_definitions[definition.name] = definition
20
+ self.amount_attribute_definitions = amount_attribute_definitions.merge(definition.name => definition).freeze
10
21
 
11
22
  define_amount_reader(definition)
12
23
  define_amount_writer(definition)
@@ -15,8 +26,13 @@ class Amount
15
26
  define_amount_validation(definition)
16
27
  end
17
28
 
18
- def amount_attribute_definitions
19
- @amount_attribute_definitions ||= {}
29
+ # Anonymous classes have no `model_name`, which Rails needs to build
30
+ # messages from error keys. Fall back to a stable placeholder so
31
+ # validations on `Class.new(ApplicationRecord)` models still report.
32
+ def model_name
33
+ return super if name
34
+
35
+ @model_name ||= ::ActiveModel::Name.new(self, nil, "AnonymousModel")
20
36
  end
21
37
 
22
38
  def amount_component_columns(name)
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Amount
4
+ module ActiveRecord
5
+ # Prepares `has_amount` attributes for Rails' bulk writes (`insert_all`,
6
+ # `upsert_all` and their variants), which skip attribute writers and take
7
+ # column values only.
8
+ module Persistence
9
+ # Turns attributes, with amounts by name, into column values. Each
10
+ # amount is cast as its writer would cast it and replaced by its
11
+ # component columns, all of them even for `nil`, so rows share keys.
12
+ # Any other key passes through.
13
+ #
14
+ # @param attributes [Hash] attributes keyed by String or Symbol
15
+ # @return [Hash]
16
+ # @raise [Amount::TypeMismatch] when a fixed-symbol amount has another
17
+ # symbol (the writer records this as a validation error instead;
18
+ # `insert_all` doesn't validate)
19
+ # @example
20
+ # UsageRecord.amount_column_values("cost" => "USDP|0.0042", "kind" => "model_call")
21
+ # # => { "cost_atomic" => 42000000, "kind" => "model_call" }
22
+ #
23
+ # UsageRecord.insert_all(rows.map { |row| UsageRecord.amount_column_values(row) })
24
+ def amount_column_values(attributes)
25
+ attributes.each_with_object({}) do |(key, value), columns|
26
+ definition = amount_attribute_definitions[key.to_sym]
27
+ next columns[key] = value unless definition
28
+
29
+ columns.merge!(definition.column_values(definition.type.cast(value)))
30
+ end
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Amount
4
+ module ActiveRecord
5
+ # Writes each `has_amount` attribute by its name, as the amount, in place
6
+ # of its component columns: `as_json` gives `"owed" => "USD|10.06"`
7
+ # rather than `"owed_atomic" => 1006`. `has_amount` includes it into the
8
+ # model that declares an amount.
9
+ #
10
+ # `only:` and `except:` take the amount's name. An amount whose columns
11
+ # weren't all selected keeps the columns that were. The raw columns stay
12
+ # readable through Rails' `attributes`.
13
+ #
14
+ # @example
15
+ # subscription.as_json # => { "id" => 1, "owed" => "USD|10.06" }
16
+ # subscription.as_json(only: :owed) # => { "owed" => "USD|10.06" }
17
+ module Serialization
18
+ # @param options [Hash, nil] Rails' options
19
+ # @return [Hash]
20
+ def serializable_hash(options = nil)
21
+ definitions = self.class.amount_attribute_definitions.values
22
+ options = amount_names_as_columns(options ? options.dup : {}, definitions)
23
+
24
+ amounts_in_place_of_columns(super(options), definitions)
25
+ end
26
+
27
+ private
28
+
29
+ # Rails filters `only:` and `except:` by column, so an amount's name
30
+ # becomes its component columns.
31
+ def amount_names_as_columns(options, definitions)
32
+ columns = definitions.to_h { |definition| [definition.name.to_s, definition.component_columns] }
33
+
34
+ %i[only except].each do |key|
35
+ next unless options.key?(key)
36
+
37
+ options[key] = Array(options[key]).flat_map { |name| columns.fetch(name.to_s) { name.to_s } }
38
+ end
39
+ options
40
+ end
41
+
42
+ # Each amount takes its atomic column's place; its symbol column drops out.
43
+ def amounts_in_place_of_columns(hash, definitions)
44
+ serialized = definitions.select { |definition| (definition.component_columns - hash.keys).empty? }
45
+ by_atomic_column = serialized.to_h { |definition| [definition.atomic_column, definition] }
46
+ symbol_columns = serialized.reject(&:fixed_symbol?).map(&:symbol_column)
47
+
48
+ hash.each_with_object({}) do |(key, value), result|
49
+ definition = by_atomic_column[key]
50
+ next result[definition.name.to_s] = public_send(definition.name) if definition
51
+
52
+ result[key] = value unless symbol_columns.include?(key)
53
+ end
54
+ end
55
+ end
56
+ end
57
+ end
@@ -7,7 +7,11 @@ require_relative "active_record/attribute_definition"
7
7
  require_relative "active_record/amount_validator"
8
8
  require_relative "active_record/type"
9
9
  require_relative "active_record/migration_methods"
10
+ require_relative "active_record/serialization"
11
+ require_relative "active_record/dirty"
10
12
  require_relative "active_record/model"
13
+ require_relative "active_record/calculations"
14
+ require_relative "active_record/persistence"
11
15
 
12
16
  class Amount
13
17
  # Optional Rails integration for ActiveRecord models and migrations.
@@ -24,6 +28,17 @@ class Amount
24
28
  # has_amount :fee, symbol: :SOL
25
29
  # end
26
30
  module ActiveRecord
31
+ # English defaults for the validator's error keys. Apps override them in
32
+ # their own locale files.
33
+ LOCALE_PATH = File.expand_path("active_record/locale/en.yml", __dir__).freeze
34
+
35
+ # Registers the gem's locale file with I18n, once.
36
+ #
37
+ # @return [void]
38
+ def self.install_locale!
39
+ ::I18n.load_path << LOCALE_PATH unless ::I18n.load_path.include?(LOCALE_PATH)
40
+ end
41
+
27
42
  # Installs the migration DSL and model macros into ActiveRecord.
28
43
  #
29
44
  # This is called automatically when the file is required.
@@ -36,9 +51,12 @@ class Amount
36
51
  end
37
52
 
38
53
  ::ActiveRecord::Base.extend(Model)
54
+ ::ActiveRecord::Base.extend(Calculations)
55
+ ::ActiveRecord::Base.extend(Persistence)
39
56
  ::ActiveRecord::Base.include(InstanceMethods)
40
57
  end
41
58
  end
42
59
  end
43
60
 
61
+ Amount::ActiveRecord.install_locale!
44
62
  Amount::ActiveRecord.install!
@@ -0,0 +1,137 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bigdecimal"
4
+
5
+ class Amount
6
+ # Internal: compact notation for large numbers, used by `ui(compact: true)`.
7
+ #
8
+ # A number of at least one thousand is divided by the largest scale it
9
+ # reaches (thousand, million, ... up to decillion, 10**33), rounded to a number of
10
+ # significant digits in the given direction, trimmed of trailing zeros and
11
+ # joined with a scale word:
12
+ #
13
+ # - when localizing, the word is `number.human.decimal_units.units.<scale>`
14
+ # (pluralized with the compacted number) joined by
15
+ # `number.human.decimal_units.format` (default `"%n %u"`), the keys Rails'
16
+ # `number_to_human` uses. A scale without a translation falls back to the
17
+ # short form below.
18
+ # - otherwise the word is `K`, `M`, `B`, `T`, `Qa`, `Qi`, `Sx`, `Sp`, `Oc`,
19
+ # `No` or `Dc`, joined as `"%n%u"`.
20
+ #
21
+ # Numbers past decillions stay in decillions (`1500Dc`).
22
+ #
23
+ # Numbers below one thousand are not compacted; {Display} formats them as
24
+ # usual.
25
+ #
26
+ # @example
27
+ # Amount::Compact.format(BigDecimal("1999999"), precision: 3, direction: :floor, locale: nil)
28
+ # # => "1.99M"
29
+ module Compact
30
+ DEFAULT_PRECISION = 3
31
+ SHORT_FORMAT = "%n%u"
32
+ LOCALE_FORMAT = "%n %u"
33
+ LOCALE_FORMAT_KEY = "number.human.decimal_units.format"
34
+ LOCALE_UNITS_KEY = "number.human.decimal_units.units"
35
+
36
+ # [exponent, I18n key, short form], smallest first.
37
+ SCALES = [
38
+ [3, :thousand, "K"],
39
+ [6, :million, "M"],
40
+ [9, :billion, "B"],
41
+ [12, :trillion, "T"],
42
+ [15, :quadrillion, "Qa"],
43
+ [18, :quintillion, "Qi"],
44
+ [21, :sextillion, "Sx"],
45
+ [24, :septillion, "Sp"],
46
+ [27, :octillion, "Oc"],
47
+ [30, :nonillion, "No"],
48
+ [33, :decillion, "Dc"]
49
+ ].freeze
50
+
51
+ module_function
52
+
53
+ # Reads the `compact:` option of `ui`.
54
+ # @param option [Boolean, Hash, nil] `true`, `false`/`nil`, or
55
+ # `{ precision: Integer }`
56
+ # @return [Integer, nil] significant digits, or `nil` when compact
57
+ # notation is off
58
+ # @raise [ArgumentError] for anything else
59
+ def precision(option)
60
+ case option
61
+ when nil, false then nil
62
+ when true then DEFAULT_PRECISION
63
+ when Hash then precision_from_hash(option)
64
+ else raise ArgumentError, "compact: must be true, false or { precision: Integer }, got #{option.inspect}"
65
+ end
66
+ end
67
+
68
+ # @param value [BigDecimal]
69
+ # @return [Boolean] whether the number is large enough to compact
70
+ def applies?(value)
71
+ value.abs >= BigDecimal(10)**SCALES.first[0]
72
+ end
73
+
74
+ # The compacted number with its scale word, e.g. `"1.5M"` or
75
+ # `"1,5 Mio."`. Call only when {applies?} is true.
76
+ # @param value [BigDecimal]
77
+ # @param precision [Integer] significant digits
78
+ # @param direction [Symbol] `:floor` or `:ceil`, as in `ui`
79
+ # @param locale [Symbol, String, nil]
80
+ # @return [String]
81
+ def format(value, precision:, direction:, locale:)
82
+ index = SCALES.rindex { |exponent, _, _| value.abs >= BigDecimal(10)**exponent }
83
+ loop do
84
+ mantissa, decimals = round(value, SCALES[index][0], precision, direction)
85
+ # Rounding up can reach the next scale: 999,999 ceils to 1000K, shown as 1M.
86
+ if mantissa.abs >= 1000 && index < SCALES.length - 1
87
+ index += 1
88
+ next
89
+ end
90
+
91
+ return join(number(mantissa, decimals, locale), mantissa, SCALES[index], locale)
92
+ end
93
+ end
94
+
95
+ # Divides by 10**exponent and rounds to `precision` significant digits.
96
+ # Returns the mantissa and how many decimals it may show.
97
+ def round(value, exponent, precision, direction)
98
+ mantissa = value / (BigDecimal(10)**exponent)
99
+ digits = [mantissa.abs.to_i.to_s.length, 1].max
100
+ decimals = precision - digits
101
+ [Display.round(mantissa, decimals, direction), [decimals, 0].max]
102
+ end
103
+
104
+ def number(mantissa, decimals, locale)
105
+ str = mantissa.to_s("F")
106
+ int, frac = str.split(".", 2)
107
+ frac = frac.to_s[0, decimals].sub(/0+\z/, "")
108
+ str = frac.empty? ? int : "#{int}.#{frac}"
109
+ locale ? Locale.apply(str, locale) : str
110
+ end
111
+
112
+ def join(number, mantissa, scale, locale)
113
+ _, key, short = scale
114
+ word = locale && Locale.translate("#{LOCALE_UNITS_KEY}.#{key}", locale, "", mantissa)
115
+ return Formattable.fill(SHORT_FORMAT, number:, label: short) if word.nil? || word.empty?
116
+
117
+ Formattable.fill(locale_format(locale), number:, label: word)
118
+ end
119
+
120
+ def locale_format(locale)
121
+ found = Locale.translate(LOCALE_FORMAT_KEY, locale, LOCALE_FORMAT)
122
+ Formattable.valid_template?(found) ? found : LOCALE_FORMAT
123
+ end
124
+
125
+ def precision_from_hash(option)
126
+ unknown = option.keys - [:precision]
127
+ raise ArgumentError, "unknown compact: option(s) #{unknown.map(&:inspect).join(', ')}" unless unknown.empty?
128
+
129
+ digits = option.fetch(:precision, DEFAULT_PRECISION)
130
+ return digits if digits.is_a?(Integer) && digits.positive?
131
+
132
+ raise ArgumentError, "compact: precision must be a positive Integer, got #{digits.inspect}"
133
+ end
134
+
135
+ private_class_method :round, :number, :join, :locale_format, :precision_from_hash
136
+ end
137
+ end
@@ -5,7 +5,7 @@ class Amount
5
5
  # `[parts, remainder]`, preserving the invariant that the parts plus
6
6
  # remainder always sum back to the receiver's atomic value (including
7
7
  # the sign).
8
- module Allocation
8
+ module Allocatable
9
9
  # Splits into equal parts and returns the leftover explicitly.
10
10
  #
11
11
  # @param n [Integer]
@@ -6,7 +6,7 @@ class Amount
6
6
  #
7
7
  # All operators preserve the receiver's class via `build`, so subclass
8
8
  # identity (`GoldAmount`) survives through `+`, `-`, `*`, `/`, `abs`, `-@`.
9
- module Arithmetic
9
+ module Calculable
10
10
  # @return [Amount]
11
11
  # @example
12
12
  # Amount.of_usdc("-1").abs
@@ -75,7 +75,10 @@ class Amount
75
75
  ensure_scalar!(other)
76
76
  raise ZeroDivisionError if other.zero?
77
77
 
78
- build((BigDecimal(@atomic) / Amount.coerce_decimal(other)).to_i)
78
+ # In Rational, so the quotient is exact before it's truncated toward
79
+ # zero. BigDecimal division rounds the quotient to a limited
80
+ # precision, which for a large amount can be off by many atomic units.
81
+ build((Rational(@atomic) / Amount.coerce_decimal(other).to_r).truncate)
79
82
  end
80
83
  end
81
84
 
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bigdecimal"
4
+
5
+ class Amount
6
+ # Concern: bringing the other side of an operation into a usable form.
7
+ #
8
+ # - {ClassMethods#coerce_decimal} turns a scalar, rate or display-unit scale
9
+ # into a `BigDecimal` without losing a `Rational`.
10
+ # - The private instance helpers bring another amount to the receiver's
11
+ # type. They only cross types through a registered directional default
12
+ # rate; without one they raise {TypeMismatch} (or return `nil` for
13
+ # comparisons). There is no implicit conversion.
14
+ module Coercible
15
+ def self.included(base)
16
+ base.extend(ClassMethods)
17
+ end
18
+
19
+ # Class-level methods extended onto any class that does `include Coercible`.
20
+ module ClassMethods
21
+ # Coerces a numeric input to BigDecimal in a way that preserves Rational
22
+ # values. `BigDecimal(value.to_s)` raises `ArgumentError` for Rational
23
+ # because `Rational#to_s` produces strings like `"3/2"`. This helper is
24
+ # the single place every call site should use to convert a scalar / rate
25
+ # / display-unit scale into a BigDecimal.
26
+ #
27
+ # @param value [Numeric, BigDecimal, Rational, String]
28
+ # @return [BigDecimal]
29
+ def coerce_decimal(value)
30
+ case value
31
+ when BigDecimal then value
32
+ when Rational then BigDecimal(value, Float::DIG + 4)
33
+ else BigDecimal(value.to_s)
34
+ end
35
+ end
36
+ end
37
+
38
+ private
39
+
40
+ def ensure_same_type!(other)
41
+ return if same_type?(other)
42
+
43
+ raise TypeMismatch, type_mismatch_message(other)
44
+ end
45
+
46
+ # The other amount in the receiver's type: itself when the types match,
47
+ # converted through a registered default rate when one exists, else `nil`.
48
+ def coerce_other_to_self_type(other)
49
+ return other if same_type?(other)
50
+ return unless other.is_a?(Amount)
51
+
52
+ other.to(symbol)
53
+ rescue Registry::NoDefaultRate
54
+ nil
55
+ end
56
+
57
+ def coerce_other_to_self_type!(other)
58
+ coerce_other_to_self_type(other) || raise(TypeMismatch, type_mismatch_message(other))
59
+ end
60
+
61
+ def type_mismatch_message(other)
62
+ "type mismatch: #{symbol} vs #{other.is_a?(Amount) ? other.symbol : other.class}"
63
+ end
64
+ end
65
+ end