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.
- checksums.yaml +4 -4
- data/.rubocop.yml +37 -0
- data/CHANGELOG.md +180 -0
- data/Gemfile +4 -0
- data/README.md +274 -2
- data/Rakefile +47 -10
- data/lib/amount/active_record/amount_validator.rb +9 -18
- data/lib/amount/active_record/attribute_definition.rb +14 -8
- data/lib/amount/active_record/calculations.rb +127 -0
- data/lib/amount/active_record/dirty.rb +43 -0
- data/lib/amount/active_record/locale/en.yml +7 -0
- data/lib/amount/active_record/model.rb +19 -3
- data/lib/amount/active_record/persistence.rb +34 -0
- data/lib/amount/active_record/serialization.rb +57 -0
- data/lib/amount/active_record.rb +18 -0
- data/lib/amount/compact.rb +137 -0
- data/lib/amount/{allocation.rb → concerns/allocatable.rb} +1 -1
- data/lib/amount/{arithmetic.rb → concerns/calculable.rb} +5 -2
- data/lib/amount/concerns/coercible.rb +65 -0
- data/lib/amount/concerns/constructible.rb +92 -0
- data/lib/amount/{conversion.rb → concerns/convertible.rb} +1 -1
- data/lib/amount/concerns/formattable.rb +112 -0
- data/lib/amount/concerns/localizable.rb +39 -0
- data/lib/amount/{comparison.rb → concerns/orderable.rb} +2 -2
- data/lib/amount/concerns/parsable.rb +58 -0
- data/lib/amount/concerns/registrable.rb +80 -0
- data/lib/amount/{serialization.rb → concerns/serializable.rb} +21 -4
- data/lib/amount/display.rb +81 -46
- data/lib/amount/locale.rb +102 -0
- data/lib/amount/registry.rb +69 -7
- data/lib/amount/ui_parser.rb +109 -0
- data/lib/amount/version.rb +1 -1
- data/lib/amount.rb +55 -199
- data/test/amount/active_record/amount_validator_test.rb +209 -0
- data/test/amount/active_record/attribute_definition_test.rb +259 -0
- data/test/amount/active_record/calculations_test.rb +165 -0
- data/test/amount/active_record/dirty_test.rb +70 -0
- data/test/amount/active_record/migration_methods_test.rb +60 -0
- data/test/amount/active_record/model_test.rb +72 -0
- data/test/amount/active_record/persistence_test.rb +53 -0
- data/test/amount/active_record/serialization_test.rb +75 -0
- data/test/amount/active_record/type_test.rb +80 -0
- data/test/amount/active_record_test.rb +12 -0
- data/test/amount/compact_test.rb +371 -0
- data/test/amount/concerns/allocatable_test.rb +166 -0
- data/test/amount/concerns/calculable_test.rb +185 -0
- data/test/amount/concerns/coercible_test.rb +49 -0
- data/test/amount/concerns/constructible_test.rb +113 -0
- data/test/amount/concerns/convertible_test.rb +54 -0
- data/test/amount/concerns/formattable_test.rb +336 -0
- data/test/amount/concerns/localizable_test.rb +59 -0
- data/test/amount/concerns/orderable_test.rb +83 -0
- data/test/amount/concerns/parsable_test.rb +98 -0
- data/test/amount/concerns/registrable_test.rb +67 -0
- data/test/amount/concerns/serializable_test.rb +136 -0
- data/test/amount/display_test.rb +181 -0
- data/test/amount/locale_test.rb +590 -0
- data/test/amount/parser_test.rb +29 -0
- data/test/amount/registry/generated_constructors_test.rb +94 -0
- data/test/amount/registry_test.rb +149 -0
- data/test/amount/ui_parser_test.rb +284 -0
- data/test/amount_test.rb +55 -0
- data/test/dummy/config/application.rb +3 -0
- data/test/generators/amount/active_record/registry_generator_test.rb +116 -0
- data/test/integration/postgresql_test.rb +124 -0
- data/test/support/active_record_test_support.rb +85 -0
- data/test/support/error_helpers.rb +22 -0
- data/test/support/locale_test_setup.rb +36 -0
- data/test/test_helper.rb +1 -0
- metadata +55 -11
- data/test/postgresql_integration_test.rb +0 -71
- data/test/test_active_record.rb +0 -375
- data/test/test_amount.rb +0 -675
- data/test/test_registry_generator.rb +0 -104
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 9a77f5a9506149f307e11d78c1063e9951c149302eaace9b35e924cf92ce4102
|
|
4
|
+
data.tar.gz: ade0b4aca169538a4b9e17d3e4ab412f19cbe343aff7b540de6936b814373751
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 0c9225c174016b40143bd049c8673312a0ceffcb32244b5ce9a613cdb2342d768faf67141ea0aeb30fe5c91d89bbf720860dae27fb77413e401d9e1877723b9b
|
|
7
|
+
data.tar.gz: 1c0dd2ff180fc3589c4a722bd0789e37b9afb7d71599680c77fcd299b2e07366df31d439647c5927ff9a8f50d1d89c07ec8de1da05fae72d9570be78e8731020
|
data/.rubocop.yml
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
require:
|
|
2
|
+
- ./rubocop/cop/amounts/one_assertion_per_test
|
|
3
|
+
- ./rubocop/cop/amounts/one_test_class_per_file
|
|
4
|
+
- ./rubocop/cop/amounts/mirrored_test_path
|
|
5
|
+
- ./rubocop/cop/amounts/concern_naming
|
|
6
|
+
|
|
1
7
|
AllCops:
|
|
2
8
|
NewCops: enable
|
|
3
9
|
SuggestExtensions: false
|
|
@@ -87,3 +93,34 @@ Gemspec/DevelopmentDependencies:
|
|
|
87
93
|
|
|
88
94
|
Gemspec/RequireMFA:
|
|
89
95
|
Enabled: false
|
|
96
|
+
|
|
97
|
+
# Project cops (rubocop/cop/amounts/). See .claude/rules/tests.md.
|
|
98
|
+
Amounts/OneAssertionPerTest:
|
|
99
|
+
Enabled: true
|
|
100
|
+
Include:
|
|
101
|
+
- "test/**/*_test.rb"
|
|
102
|
+
- "spec/**/*_spec.rb"
|
|
103
|
+
|
|
104
|
+
Amounts/OneTestClassPerFile:
|
|
105
|
+
Enabled: true
|
|
106
|
+
Include:
|
|
107
|
+
- "test/**/*_test.rb"
|
|
108
|
+
- "spec/**/*_spec.rb"
|
|
109
|
+
|
|
110
|
+
Amounts/MirroredTestPath:
|
|
111
|
+
Enabled: true
|
|
112
|
+
Include:
|
|
113
|
+
- "test/**/*_test.rb"
|
|
114
|
+
- "spec/**/*_spec.rb"
|
|
115
|
+
# These directories don't mirror lib/ (see .claude/rules/tests.md).
|
|
116
|
+
Exclude:
|
|
117
|
+
- "test/support/**/*"
|
|
118
|
+
- "test/dummy/**/*"
|
|
119
|
+
- "test/integration/**/*"
|
|
120
|
+
- "spec/support/**/*"
|
|
121
|
+
|
|
122
|
+
# See .claude/rules/concerns.md.
|
|
123
|
+
Amounts/ConcernNaming:
|
|
124
|
+
Enabled: true
|
|
125
|
+
Include:
|
|
126
|
+
- "lib/amount/concerns/**/*.rb"
|
data/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,185 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.0 - 2026-11-14
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- `amount_changes` and `saved_amount_changes` on models with `has_amount`:
|
|
8
|
+
Rails' `changes` and `saved_changes` with each amount by name, as
|
|
9
|
+
`[before, after]` Amounts, in place of its component columns. Rails' own
|
|
10
|
+
change hashes are unchanged.
|
|
11
|
+
- `Model.amount_column_values(attributes)` turns attributes, with amounts by
|
|
12
|
+
name, into column values for `insert_all`, `upsert_all` and their variants,
|
|
13
|
+
which skip attribute writers. Each amount is cast as its writer would cast
|
|
14
|
+
it and replaced by its component columns (all of them even for `nil`, so
|
|
15
|
+
rows share keys); other keys pass through. A fixed-symbol amount in another
|
|
16
|
+
symbol raises `Amount::TypeMismatch`, since bulk writes skip validations.
|
|
17
|
+
- SQL aggregates for `has_amount` attributes that return Amounts:
|
|
18
|
+
`sum_amount`, `minimum_amount`, `maximum_amount` and `average_amount`. Each
|
|
19
|
+
runs one query in the scope of the relation it's called on, so `where`,
|
|
20
|
+
`group` and associations apply. Grouped, the result is keyed like Rails'
|
|
21
|
+
`group(...).sum`. A multi-symbol attribute with more than one symbol in
|
|
22
|
+
scope, or in one group, raises `Amount::TypeMismatch`; group by its symbol
|
|
23
|
+
column for one Amount per symbol. A fixed-symbol sum over no rows is zero;
|
|
24
|
+
other empty results are `nil`. `average_amount` truncates toward zero to a
|
|
25
|
+
whole atomic unit, as `Amount#/` does. Grouping by an association name
|
|
26
|
+
raises `ArgumentError` (group by its foreign key). On SQLite, aggregates
|
|
27
|
+
past 64 bits raise `integer overflow` or come back inexact; PostgreSQL is
|
|
28
|
+
exact.
|
|
29
|
+
|
|
30
|
+
### Changed
|
|
31
|
+
|
|
32
|
+
- **Breaking:** a model with `has_amount` serializes each amount by its name,
|
|
33
|
+
as its exact compact string, in place of its component columns:
|
|
34
|
+
`as_json` gives `"owed" => "USD|10.06"`, not `"owed_atomic" => "1006.0"`
|
|
35
|
+
(`serializable_hash` holds the Amount). `only:` and `except:` take the
|
|
36
|
+
amount's name. `has_amount` includes this into the declaring model;
|
|
37
|
+
`ActiveRecord::Base` and models without amounts are unchanged.
|
|
38
|
+
|
|
39
|
+
Migration: JSON readers that read `<name>_atomic` / `<name>_symbol` read
|
|
40
|
+
`<name>` instead and parse it with `Amount.parse`. Code that needs the raw
|
|
41
|
+
columns reads them from `attributes`
|
|
42
|
+
(`record.attributes.slice("owed_atomic")`).
|
|
43
|
+
- **Breaking:** `Amount#as_json` (and so `to_json`) writes the exact compact
|
|
44
|
+
string: whole units with exactly the symbol's `decimals` places
|
|
45
|
+
(`"USDC|1.500000"`, `"SOL|1.123456789"`). It previously returned `to_s`,
|
|
46
|
+
which rounds down to `ui_decimals`, so JSON silently dropped digits past it
|
|
47
|
+
(`"SOL|1.1234"` for 1.123456789 SOL).
|
|
48
|
+
|
|
49
|
+
Migration: clients that read the value with `Amount.parse` or as a number
|
|
50
|
+
need no change. Where JSON output was compared as a string (tests,
|
|
51
|
+
fixtures) or shown to people, expect the longer form, or use `to_s` or `ui`
|
|
52
|
+
for display.
|
|
53
|
+
|
|
54
|
+
### Fixed
|
|
55
|
+
|
|
56
|
+
- `Amount#/` by a scalar computes the quotient exactly (in `Rational`) before
|
|
57
|
+
truncating it toward zero. It divided in `BigDecimal`, which rounds the
|
|
58
|
+
quotient to a limited precision, so large amounts divided by small decimals
|
|
59
|
+
came out wrong: 10^40 atomic units divided by `BigDecimal("7e-21")` was off
|
|
60
|
+
by 1429 atomic units. Results that were already exact are unchanged.
|
|
61
|
+
`average_amount` divides this way.
|
|
62
|
+
- A subclass of a model with `has_amount` (STI included) inherits its
|
|
63
|
+
parent's amount definitions. It previously started with none, so
|
|
64
|
+
`amount_attribute_definitions`, `amount_atomic_column` and friends raised
|
|
65
|
+
`KeyError` on the subclass, and so did the `amount:` validator and the
|
|
66
|
+
`have_amount_column` matcher for inherited amounts. Amounts a subclass
|
|
67
|
+
declares stay off its parent and siblings. `amount_attribute_definitions`
|
|
68
|
+
is now a `class_attribute` holding a frozen Hash.
|
|
69
|
+
|
|
70
|
+
## 0.1.0 - 2026-11-02
|
|
71
|
+
|
|
72
|
+
### Added
|
|
73
|
+
|
|
74
|
+
- Compact notation for large numbers: `ui(compact: true)` renders `50M TOKENS`
|
|
75
|
+
or `$1.5M`. It keeps 3 significant digits (`compact: { precision: 2 }` to
|
|
76
|
+
change it), rounds in `direction:` (so `1_999_999` floors to `1.99M`), trims
|
|
77
|
+
trailing zeros and moves up a scale when rounding reaches it. Numbers below
|
|
78
|
+
one thousand are formatted as usual. Scale words run from `K`/`M`/`B`/`T`
|
|
79
|
+
through `Qa`/`Qi`/`Sx`/`Sp`/`Oc`/`No` to `Dc` (decillion, 10^33), joined
|
|
80
|
+
as `"%n%u"`; when localizing they come from
|
|
81
|
+
`number.human.decimal_units.units` (pluralized with the compacted number)
|
|
82
|
+
joined by `number.human.decimal_units.format` (default `"%n %u"`), falling
|
|
83
|
+
back to the short form for a missing word. Works with `unit:` (the scaled
|
|
84
|
+
number is compacted), labels and templates (which wrap the compacted
|
|
85
|
+
number; plural labels agree with the full value) and `decorated: false`.
|
|
86
|
+
Output without `compact:` is unchanged.
|
|
87
|
+
- `Amount.parse_ui(input, symbol, locale: nil)` parses what a person types in a
|
|
88
|
+
locale's number format: `parse_ui("1.500,50", :USD, locale: :de)` and
|
|
89
|
+
`parse_ui("1,500.50", :USD, locale: :en)` both give `USD|1500.50`. The
|
|
90
|
+
effective locale is `locale:`, then `I18n.locale` when `Amount.localize` is
|
|
91
|
+
true, else plain parsing (`.` decimal, no delimiters). Accepts surrounding
|
|
92
|
+
whitespace (including NBSP), a leading `-` or `+`, delimiters in correct
|
|
93
|
+
groups of three, and the type's label or display symbol at either end in any
|
|
94
|
+
plural form (`"$1,500.50"`, `"1.500,50 €"`). Raises `InvalidInput` for more
|
|
95
|
+
decimals than the type has (never rounds), misplaced delimiters, a repeated
|
|
96
|
+
separator, another type's label, or empty input. Returns the type's
|
|
97
|
+
registered class; an unregistered symbol raises as `Amount.new` does.
|
|
98
|
+
`Amount.parse` and the constructors are unchanged. Wiring it into the
|
|
99
|
+
ActiveRecord type is not part of this change.
|
|
100
|
+
- Templates for where the number and unit go. `register` takes
|
|
101
|
+
`display_format:` and display unit specs take `format:`, where `%n` is the
|
|
102
|
+
formatted number (sign included) and `%u` the label: `"%u%n"`,
|
|
103
|
+
`"%n\u00A0%u"`. Templates are used exactly as given, so non-breaking spaces
|
|
104
|
+
survive. When localizing, `amounts.formats.<symbol downcased>` and
|
|
105
|
+
`amounts.display_unit_formats.<symbol downcased>.<unit>` override them; a
|
|
106
|
+
locale template without `%n` is ignored. `display_position` stays as
|
|
107
|
+
shorthand for `"%u%n"` / `"%n %u"`, so existing output is unchanged.
|
|
108
|
+
Passing both `display_format:` and `display_position:` raises
|
|
109
|
+
`ArgumentError`; a display unit with both `:format` and `:position` raises
|
|
110
|
+
`InvalidDisplayUnit`. `Registry::Entry#display_format` always holds the
|
|
111
|
+
type's template, and `#display_position` is `nil` for a type registered
|
|
112
|
+
with `display_format:`.
|
|
113
|
+
- `Amount#display_format(unit: nil, locale: nil)` returns the template `ui`
|
|
114
|
+
uses for the type or a display unit, with the same locale precedence.
|
|
115
|
+
Template behavior lives in the new `Amount::Formattable` concern, included
|
|
116
|
+
in `Amount`.
|
|
117
|
+
- `Registry::Entry#display_unit(unit)` returns a display unit's spec, raising
|
|
118
|
+
`InvalidDisplayUnit` for an unknown unit.
|
|
119
|
+
- Plural unit labels. `display_symbol:` (and a display unit's `symbol:`) accept
|
|
120
|
+
a hash such as `{ one: "search", other: "searches" }`, giving `1 search` /
|
|
121
|
+
`2 searches`. `register` raises (`Registry::InvalidDisplaySymbol`, or
|
|
122
|
+
`InvalidDisplayUnit` for a unit) unless the hash has `:other` and maps
|
|
123
|
+
Symbols to Strings. The count is the displayed number (after scaling and
|
|
124
|
+
rounding). Without localizing, `:one` is used when it equals 1, else
|
|
125
|
+
`:other`; when localizing, I18n translations and hashes are pluralized with
|
|
126
|
+
`count:` through the locale's rules (`few`, `many`, ...). A missing form falls
|
|
127
|
+
back to `:other`. `unit_label` takes `count:`; without it the `:other` form is
|
|
128
|
+
used. String labels are unchanged.
|
|
129
|
+
- Unit labels can come from I18n. `register` takes `label_key:` (String or
|
|
130
|
+
Symbol); without it the key is `amounts.units.<symbol downcased>`. Display
|
|
131
|
+
units take `label_key:` in their spec, defaulting to
|
|
132
|
+
`amounts.display_units.<symbol downcased>.<unit>`. Lookups only happen when
|
|
133
|
+
localizing (`locale:` or `Amount.localize = true`). Fallbacks: a type falls
|
|
134
|
+
back to `display_symbol`; a display unit to its `:symbol`, then the type's
|
|
135
|
+
label. A missing key never renders "translation missing". Output is
|
|
136
|
+
unchanged when not localizing.
|
|
137
|
+
- `Amount#unit_label(unit: nil, locale: nil)` returns the label alone, with
|
|
138
|
+
the same rules as `ui`, for column headers and chips.
|
|
139
|
+
- `ui` can format numbers for a locale: `ui(locale: :de)` uses the locale's
|
|
140
|
+
`number.format` delimiter and separator (`"$122.500,00"`), falling back to
|
|
141
|
+
`,` and `.` for missing keys. Works with `unit:`, `decorated: false`,
|
|
142
|
+
`trim_zeros` and `direction`.
|
|
143
|
+
- `Amount.localize = true` makes `ui` use `I18n.locale` when no `locale:` is
|
|
144
|
+
given. It defaults to `false`, so output is unchanged unless you opt in.
|
|
145
|
+
Passing `locale:` or setting `Amount.localize = true` without the `i18n` gem
|
|
146
|
+
loaded raises `ArgumentError`. `to_s`, `formatted`, `as_json`, serialization
|
|
147
|
+
and `Amount.parse` never change with the locale.
|
|
148
|
+
|
|
149
|
+
### Changed
|
|
150
|
+
|
|
151
|
+
- `Amount`'s internal concern modules are renamed as -able adjectives and live
|
|
152
|
+
in `lib/amount/concerns/`: `Arithmetic` → `Calculable`, `Allocation` →
|
|
153
|
+
`Allocatable`, `Comparison` → `Orderable`, `Conversion` → `Convertible`,
|
|
154
|
+
`Serialization` → `Serializable` (`Formattable` is unchanged). Five new
|
|
155
|
+
concerns hold logic that used to sit in `Amount` itself: `Registrable`,
|
|
156
|
+
`Localizable`, `Parsable`, `Constructible` and `Coercible`. None of these
|
|
157
|
+
modules are documented API, and every `Amount` method is unchanged. Code
|
|
158
|
+
that referenced a module by name, or required a file under `amount/`
|
|
159
|
+
other than the documented entry points, should `require "amount"` and call
|
|
160
|
+
`Amount`'s methods.
|
|
161
|
+
- `AmountValidator` now adds errors by I18n key instead of hard-coded English
|
|
162
|
+
strings, so apps can translate or reword them: `:amount_type`,
|
|
163
|
+
`:amount_symbol`, `:amount_invalid_constraint`, `:amount_incomparable`, plus
|
|
164
|
+
Rails' own `:greater_than`, `:greater_than_or_equal_to`, `:less_than`,
|
|
165
|
+
`:less_than_or_equal_to` and `:invalid`. English defaults ship in
|
|
166
|
+
`lib/amount/active_record/locale/en.yml`, loaded into `I18n.load_path` when
|
|
167
|
+
`amount/active_record` is required (once, with or without Rails). With no app
|
|
168
|
+
translations, message text is unchanged. `errors.details` now reports the
|
|
169
|
+
keys and interpolation values.
|
|
170
|
+
|
|
171
|
+
### Fixed
|
|
172
|
+
|
|
173
|
+
- Anonymous ActiveRecord classes using `has_amount` get a fallback
|
|
174
|
+
`model_name`, so validation messages can be generated for them.
|
|
175
|
+
- On Rails 8.1, assigning an amount whose atomic value has more than 16 digits
|
|
176
|
+
(`Amount.new(10**30, :SOL, from: :atomic)`) silently truncated it before
|
|
177
|
+
saving (to `10**15`). Rails 8.1 cuts a string cast to an integer column to
|
|
178
|
+
16 bytes, and `has_amount` wrote the atomic value as a string. It now writes
|
|
179
|
+
the Integer, which every Rails version stores exactly. Reads were never
|
|
180
|
+
affected; rows already written under Rails 8.1 with more than 16 digits
|
|
181
|
+
hold the truncated value.
|
|
182
|
+
|
|
3
183
|
## 0.0.8 - 2026-05-05
|
|
4
184
|
|
|
5
185
|
### Changed
|
data/Gemfile
CHANGED
data/README.md
CHANGED
|
@@ -150,6 +150,10 @@ Amount.new("10", :USDC) / 2
|
|
|
150
150
|
# => #<Amount USDC|5.0>
|
|
151
151
|
```
|
|
152
152
|
|
|
153
|
+
The quotient is computed exactly and truncated toward zero to a whole atomic
|
|
154
|
+
unit: `Amount.new(3, :USDC, from: :atomic) / 2` is 1 atomic unit, and `-3 / 2`
|
|
155
|
+
is -1.
|
|
156
|
+
|
|
153
157
|
`split` and `allocate` return explicit remainders:
|
|
154
158
|
|
|
155
159
|
```ruby
|
|
@@ -215,8 +219,193 @@ amount.ui
|
|
|
215
219
|
amount.ui(direction: :ceil)
|
|
216
220
|
amount.ui(unit: :gram)
|
|
217
221
|
amount.in_unit(:gram)
|
|
222
|
+
amount.ui(locale: :de) # => "$122.500,00" (needs the i18n gem)
|
|
223
|
+
amount.ui(compact: true) # => "$1.5M" for 1,500,000
|
|
224
|
+
|
|
225
|
+
Amount.localize = true # ui follows I18n.locale
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
`ui` formats numbers for a locale (thousands delimiter and decimal separator
|
|
229
|
+
from `number.format`) only when you pass `locale:` or set `Amount.localize = true`.
|
|
230
|
+
Both require I18n to be loaded and raise `ArgumentError` otherwise. `to_s`,
|
|
231
|
+
`formatted`, serialization and `Amount.parse` never depend on the locale.
|
|
232
|
+
|
|
233
|
+
Unit labels can be translated too. When localizing, the label comes from the
|
|
234
|
+
type's `label_key:` (default `amounts.units.<symbol downcased>`), then falls back
|
|
235
|
+
to `display_symbol`. Display units use their spec's `label_key:` (default
|
|
236
|
+
`amounts.display_units.<symbol downcased>.<unit>`), then the unit's `:symbol`,
|
|
237
|
+
then the type's label. Missing keys never yield "translation missing".
|
|
238
|
+
|
|
239
|
+
```yaml
|
|
240
|
+
en:
|
|
241
|
+
amounts:
|
|
242
|
+
display_units:
|
|
243
|
+
gold: { oz_t: "oz t", gram: "g", kg: "kg" }
|
|
244
|
+
de:
|
|
245
|
+
amounts:
|
|
246
|
+
display_units:
|
|
247
|
+
gold: { oz_t: "Feinunze", gram: "Gramm", kg: "Kilogramm" }
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
```ruby
|
|
251
|
+
gold = Amount.of_gold("12.5") # :GOLD with oz_t / gram / kg display units
|
|
252
|
+
|
|
253
|
+
gold.ui(unit: :gram, locale: :en) # => "388.79 g"
|
|
254
|
+
gold.ui(unit: :gram, locale: :de) # => "388,79 Gramm"
|
|
255
|
+
gold.ui(unit: :kg, locale: :de) # => "0,38879 Kilogramm"
|
|
256
|
+
gold.unit_label(unit: :kg, locale: :de) # => "Kilogramm"
|
|
257
|
+
gold.unit_label(unit: :gram) # => "g" (not localizing)
|
|
258
|
+
|
|
259
|
+
Amount.register :SEARCHES, decimals: 0, label_key: "amounts.units.searches"
|
|
260
|
+
Amount.of_searches(3).unit_label(locale: :de) # => "Suchen" (with that key in de)
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
`unit_label(unit: nil, locale: nil, count: nil)` returns the label alone, following
|
|
264
|
+
the same rules as `ui`.
|
|
265
|
+
|
|
266
|
+
### Parsing typed input
|
|
267
|
+
|
|
268
|
+
`Amount.parse_ui` reads what a person types, in a locale's number format. The
|
|
269
|
+
locale is `locale:`, then `I18n.locale` when `Amount.localize` is true, else
|
|
270
|
+
plain parsing (`.` decimal, no delimiters). `Amount.parse` stays the compact
|
|
271
|
+
wire format.
|
|
272
|
+
|
|
273
|
+
```ruby
|
|
274
|
+
Amount.parse_ui("1.500,50", :USD, locale: :de) # => USD|1500.50
|
|
275
|
+
Amount.parse_ui("1,500.50", :USD, locale: :en) # => USD|1500.50
|
|
276
|
+
Amount.parse_ui("1500.50", :USD) # => USD|1500.50
|
|
277
|
+
Amount.parse_ui("1.500,50 €", :EUR, locale: :de) # label at either end, any plural form
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
It accepts surrounding whitespace (including NBSP), a leading `-` or `+`, and
|
|
281
|
+
delimiters in groups of three. It raises `Amount::InvalidInput` for more
|
|
282
|
+
decimal places than the type has (it never rounds), misplaced delimiters
|
|
283
|
+
(`"1,50,0"`), a repeated separator, another type's label, or empty input.
|
|
284
|
+
`ui(locale:)` output round-trips through `parse_ui(..., locale:)`.
|
|
285
|
+
|
|
286
|
+
### Plural labels
|
|
287
|
+
|
|
288
|
+
Labels can agree with the number: `1 search`, `2 searches`. `count` is the
|
|
289
|
+
number as displayed, after unit scaling and rounding (`direction:`) and before
|
|
290
|
+
formatting, so `1.00` is one and `1.50` is other.
|
|
291
|
+
|
|
292
|
+
In code, without I18n, give `display_symbol:` (or a display unit's `symbol:`) a
|
|
293
|
+
hash. It must have `:other`; `register` raises otherwise.
|
|
294
|
+
|
|
295
|
+
```ruby
|
|
296
|
+
Amount.register :SEARCHES, decimals: 0, display_symbol: { one: "search", other: "searches" }
|
|
297
|
+
|
|
298
|
+
Amount.of_searches(1).ui # => "1 search"
|
|
299
|
+
Amount.of_searches(0).ui # => "0 searches"
|
|
300
|
+
Amount.of_searches(2).ui # => "2 searches"
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
The hash uses `:one` when the displayed number equals 1, else `:other`. When
|
|
304
|
+
localizing with I18n loaded, the locale's pluralization rules decide instead,
|
|
305
|
+
so a hash can carry `few`, `many`, ... too. I18n translations can be plural
|
|
306
|
+
hashes as well:
|
|
307
|
+
|
|
308
|
+
```yaml
|
|
309
|
+
en:
|
|
310
|
+
amounts:
|
|
311
|
+
units:
|
|
312
|
+
searches:
|
|
313
|
+
one: "search"
|
|
314
|
+
other: "searches"
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
`unit_label(count: nil)` takes the same behavior; without a number it uses
|
|
318
|
+
`:other`: `Amount.of_searches(1).unit_label(count: 1) # => "search"`.
|
|
319
|
+
String labels behave exactly as before.
|
|
320
|
+
|
|
321
|
+
Where the number and label go is a template, like Rails'
|
|
322
|
+
`number.currency.format.format`: `%n` is the formatted number (sign included)
|
|
323
|
+
and `%u` the label. Set it with `display_format:` on `register` or `format:` on
|
|
324
|
+
a display unit. `display_position` is shorthand for one: `:prefix` is `"%u%n"`
|
|
325
|
+
and `:suffix` (the default) is `"%n %u"`. A type takes one or the other;
|
|
326
|
+
passing both raises `ArgumentError`.
|
|
327
|
+
|
|
328
|
+
```ruby
|
|
329
|
+
Amount.register :EUR, decimals: 2, display_symbol: "€", display_format: "%u%n"
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
When localizing, `amounts.formats.<symbol downcased>` (and
|
|
333
|
+
`amounts.display_unit_formats.<symbol downcased>.<unit>` for display units)
|
|
334
|
+
overrides the configured template:
|
|
335
|
+
|
|
336
|
+
```yaml
|
|
337
|
+
de:
|
|
338
|
+
amounts:
|
|
339
|
+
formats:
|
|
340
|
+
eur: "%n\u00A0%u" # non-breaking space: "12,50 €" never wraps apart
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
```ruby
|
|
344
|
+
Amount.of_eur("12.5").ui(locale: :en) # => "€12.50"
|
|
345
|
+
Amount.of_eur("12.5").ui(locale: :de) # => "12,50\u00A0€"
|
|
346
|
+
Amount.of_eur("12.5").ui(locale: :de, decorated: false) # => "12,50"
|
|
347
|
+
```
|
|
348
|
+
|
|
349
|
+
Templates are used exactly as given; nothing inserts non-breaking spaces for
|
|
350
|
+
you, so put them in your locale files. Negative numbers keep their sign inside
|
|
351
|
+
`%n` (`"$-5.00"`).
|
|
352
|
+
|
|
353
|
+
`display_format(unit: nil, locale: nil)` returns the template `ui` would use,
|
|
354
|
+
for rendering the number and label yourself:
|
|
355
|
+
|
|
356
|
+
```ruby
|
|
357
|
+
Amount.of_eur("12.5").display_format(locale: :de) # => "%n\u00A0%u"
|
|
358
|
+
```
|
|
359
|
+
|
|
360
|
+
### Compact notation
|
|
361
|
+
|
|
362
|
+
`ui(compact: true)` shortens numbers of one thousand or more: `50M`, `$1.5M`.
|
|
363
|
+
It keeps 3 significant digits (`compact: { precision: 2 }` changes that),
|
|
364
|
+
rounds in `direction:` (floor by default, so `1_999_999` is `1.99M`, never
|
|
365
|
+
`2M`) and trims trailing zeros. Below one thousand the number is formatted as
|
|
366
|
+
usual. Not using `compact:` leaves output unchanged.
|
|
367
|
+
|
|
368
|
+
```ruby
|
|
369
|
+
Amount.register :TOKENS, decimals: 0
|
|
370
|
+
|
|
371
|
+
Amount.of_tokens(50_000_000).ui(compact: true) # => "50M TOKENS"
|
|
372
|
+
Amount.of_tokens(1_999_999).ui(compact: true) # => "1.99M TOKENS"
|
|
373
|
+
Amount.of_tokens(1_999_999).ui(compact: true, direction: :ceil) # => "2M TOKENS"
|
|
374
|
+
Amount.of_tokens(1_299_999).ui(compact: { precision: 2 }) # => "1.2M TOKENS"
|
|
375
|
+
Amount.of_tokens(50_000_000).ui(compact: true, decorated: false) # => "50M"
|
|
376
|
+
Amount.of_usd("1500000").ui(compact: true) # => "$1.5M"
|
|
377
|
+
Amount.of_gold("1000").ui(unit: :gram, compact: true) # => "31.1K g"
|
|
378
|
+
```
|
|
379
|
+
|
|
380
|
+
Not localizing, the scale words are `K`, `M`, `B`, `T`, `Qa` (quadrillion),
|
|
381
|
+
`Qi` (quintillion), `Sx`, `Sp`, `Oc`, `No` and `Dc` (decillion, 10^33), joined
|
|
382
|
+
as `"%n%u"`. When localizing, they come from `number.human.decimal_units.units`
|
|
383
|
+
(`thousand`, `million`, `billion`, `trillion`, `quadrillion`, `quintillion`,
|
|
384
|
+
`sextillion`, `septillion`, `octillion`, `nonillion`, `decillion`, optionally
|
|
385
|
+
plural hashes counted with the compacted number), joined by
|
|
386
|
+
`number.human.decimal_units.format` (default `"%n %u"`), the same keys Rails'
|
|
387
|
+
`number_to_human` reads (Rails itself stops at `quadrillion`). A scale with no
|
|
388
|
+
translation falls back to its short form. Numbers past decillions stay in
|
|
389
|
+
decillions (`1500Dc`).
|
|
390
|
+
|
|
391
|
+
```yaml
|
|
392
|
+
de:
|
|
393
|
+
number:
|
|
394
|
+
human:
|
|
395
|
+
decimal_units:
|
|
396
|
+
format: "%n %u"
|
|
397
|
+
units: { thousand: "Tsd.", million: "Mio.", billion: "Mrd." }
|
|
398
|
+
amounts:
|
|
399
|
+
units: { tokens: "Token" }
|
|
400
|
+
```
|
|
401
|
+
|
|
402
|
+
```ruby
|
|
403
|
+
Amount.of_tokens(1_500_000).ui(compact: true, locale: :de) # => "1,5 Mio. Token"
|
|
218
404
|
```
|
|
219
405
|
|
|
406
|
+
The type's label and template wrap the compacted number, and a plural label
|
|
407
|
+
agrees with the full value (`1K searches`), not the compacted digits.
|
|
408
|
+
|
|
220
409
|
### Serialization
|
|
221
410
|
|
|
222
411
|
```ruby
|
|
@@ -224,6 +413,15 @@ payload = amount.to_h
|
|
|
224
413
|
Amount.load(payload)
|
|
225
414
|
```
|
|
226
415
|
|
|
416
|
+
`as_json` (and so `to_json`) writes the exact compact string: whole units with
|
|
417
|
+
exactly the symbol's `decimals` places. It ignores display settings and never
|
|
418
|
+
rounds, so `Amount.parse` reads it back exactly. Use `to_s` or `ui` for display.
|
|
419
|
+
|
|
420
|
+
```ruby
|
|
421
|
+
Amount.of_usdc("1.5").as_json # => "USDC|1.500000"
|
|
422
|
+
{ amount: Amount.of_usdc("1.5") }.to_json # => '{"amount":"USDC|1.500000"}'
|
|
423
|
+
```
|
|
424
|
+
|
|
227
425
|
## Registry API
|
|
228
426
|
|
|
229
427
|
```ruby
|
|
@@ -297,6 +495,34 @@ Writers accept:
|
|
|
297
495
|
- `Hash` payloads
|
|
298
496
|
- raw numeric values for fixed-symbol attributes only
|
|
299
497
|
|
|
498
|
+
A subclass (STI included) inherits its parent's amounts. Amounts it declares
|
|
499
|
+
itself stay off the parent and its other subclasses.
|
|
500
|
+
|
|
501
|
+
`as_json`, `to_json` and `serializable_hash` write each amount by its name, as
|
|
502
|
+
its exact compact string, in place of its columns. `only:` and `except:` take the
|
|
503
|
+
amount's name, and the raw columns stay readable through `attributes`.
|
|
504
|
+
`amount_changes` and `saved_amount_changes` are `changes` and `saved_changes`
|
|
505
|
+
with amounts by name. Rails' own change hashes stay keyed by column:
|
|
506
|
+
|
|
507
|
+
```ruby
|
|
508
|
+
holding.as_json # => { "id" => 1, "amount" => "USDC|1.500000", "fee" => "SOL|0.250000000" }
|
|
509
|
+
|
|
510
|
+
holding.update!(amount: "USDC|2")
|
|
511
|
+
holding.saved_amount_changes # => { "amount" => [#<Amount USDC $1.50>, #<Amount USDC $2.00>] }
|
|
512
|
+
```
|
|
513
|
+
|
|
514
|
+
`insert_all` and `upsert_all` skip writers, so `amount_column_values` turns
|
|
515
|
+
amounts by name into their columns first. It casts like the writer, raises
|
|
516
|
+
`Amount::TypeMismatch` for a fixed-symbol amount in another symbol, and gives
|
|
517
|
+
every column of a `nil` amount so rows share keys:
|
|
518
|
+
|
|
519
|
+
```ruby
|
|
520
|
+
Holding.amount_column_values(amount: "USDC|1.50", fee: 0.25)
|
|
521
|
+
# => { "amount_atomic" => 1500000, "amount_symbol" => "USDC", "fee_atomic" => 250000000 }
|
|
522
|
+
|
|
523
|
+
Holding.insert_all(rows.map { |row| Holding.amount_column_values(row) })
|
|
524
|
+
```
|
|
525
|
+
|
|
300
526
|
Scopes:
|
|
301
527
|
|
|
302
528
|
```ruby
|
|
@@ -309,6 +535,23 @@ Holding.where_amount_between("USDC|1.00", "USDC|5.00")
|
|
|
309
535
|
Holding.amount_in(:USDC)
|
|
310
536
|
```
|
|
311
537
|
|
|
538
|
+
Aggregates run in SQL and return Amounts, one query each, in the scope they're
|
|
539
|
+
called on (`where`, `group` and associations apply):
|
|
540
|
+
|
|
541
|
+
```ruby
|
|
542
|
+
Holding.sum_amount(:fee) # => #<Amount SOL ...>
|
|
543
|
+
Holding.minimum_amount(:fee)
|
|
544
|
+
Holding.maximum_amount(:fee)
|
|
545
|
+
Holding.average_amount(:fee) # truncated toward zero, like Amount#/
|
|
546
|
+
Holding.group(:amount_symbol).sum_amount(:amount) # => { "USDC" => #<Amount USDC ...>, "SOL" => ... }
|
|
547
|
+
```
|
|
548
|
+
|
|
549
|
+
Symbols never mix: a multi-symbol attribute with more than one symbol in scope
|
|
550
|
+
(or in one group) raises `Amount::TypeMismatch`, so group by its symbol column for
|
|
551
|
+
one Amount per symbol. A fixed-symbol sum over no rows is zero; otherwise an
|
|
552
|
+
empty set gives `nil`. Group by a column or SQL expression, not an association
|
|
553
|
+
name.
|
|
554
|
+
|
|
312
555
|
Suggested check constraint for multi-symbol amounts:
|
|
313
556
|
|
|
314
557
|
```sql
|
|
@@ -316,9 +559,38 @@ ALTER TABLE holdings ADD CONSTRAINT amount_both_or_neither
|
|
|
316
559
|
CHECK ((amount_atomic IS NULL) = (amount_symbol IS NULL));
|
|
317
560
|
```
|
|
318
561
|
|
|
562
|
+
### Validation messages
|
|
563
|
+
|
|
564
|
+
`validates :amount, amount: { symbol: :USDC, greater_than: 0 }` adds errors by
|
|
565
|
+
I18n key, so apps can translate or reword them. The English defaults ship in
|
|
566
|
+
`lib/amount/active_record/locale/en.yml`, which the gem adds to `I18n.load_path`
|
|
567
|
+
when `amount/active_record` loads (Rails or plain ActiveRecord).
|
|
568
|
+
|
|
569
|
+
| Case | Key | Interpolations | English default |
|
|
570
|
+
|---|---|---|---|
|
|
571
|
+
| Not an Amount | `:amount_type` | | `must be an Amount` |
|
|
572
|
+
| Wrong symbol | `:amount_symbol` | `expected` | `must have symbol %{expected}` |
|
|
573
|
+
| Invalid constraint | `:amount_invalid_constraint` | `option`, `message` | `has invalid %{option} constraint: %{message}` |
|
|
574
|
+
| Incomparable | `:amount_incomparable` | `symbol`, `other_symbol`, `option` | `cannot compare %{symbol} to %{other_symbol} for %{option}` |
|
|
575
|
+
| Comparisons | Rails' `:greater_than`, `:greater_than_or_equal_to`, `:less_than`, `:less_than_or_equal_to` | `count` (the other amount's `to_s`) | Rails' own, e.g. `must be greater than %{count}` |
|
|
576
|
+
| Fallback | Rails' `:invalid` | | `is invalid` |
|
|
577
|
+
|
|
578
|
+
Override any of them in your own locale files:
|
|
579
|
+
|
|
580
|
+
```yaml
|
|
581
|
+
de:
|
|
582
|
+
errors:
|
|
583
|
+
messages:
|
|
584
|
+
amount_symbol: "muss das Symbol %{expected} haben"
|
|
585
|
+
```
|
|
586
|
+
|
|
587
|
+
`record.errors.details` reports the keys and interpolation values.
|
|
588
|
+
Apps that already translate Rails' `greater_than` etc. get those translations
|
|
589
|
+
for free.
|
|
590
|
+
|
|
319
591
|
### SQLite Note
|
|
320
592
|
|
|
321
|
-
The adapter supports SQLite for general integration tests and development, but SQLite does not preserve `DECIMAL(78,0)` values above 64-bit range exactly under ActiveRecord's default numeric handling. For exact wei-scale persistence, use PostgreSQL or another database with true arbitrary-precision numeric behavior.
|
|
593
|
+
The adapter supports SQLite for general integration tests and development, but SQLite does not preserve `DECIMAL(78,0)` values above 64-bit range exactly under ActiveRecord's default numeric handling, and its sums and averages past that range either raise `integer overflow` or come back inexact (Rails' own `sum` too). For exact wei-scale persistence, use PostgreSQL or another database with true arbitrary-precision numeric behavior.
|
|
322
594
|
|
|
323
595
|
### PostgreSQL Dummy App
|
|
324
596
|
|
|
@@ -334,7 +606,7 @@ Run the PostgreSQL integration test explicitly:
|
|
|
334
606
|
|
|
335
607
|
```bash
|
|
336
608
|
AMOUNTS_POSTGRES_URL=postgresql://localhost/amounts_test \
|
|
337
|
-
bundle exec
|
|
609
|
+
bundle exec rake test:integration
|
|
338
610
|
```
|
|
339
611
|
|
|
340
612
|
If `AMOUNTS_POSTGRES_URL` is not set, the PostgreSQL test file skips cleanly.
|
data/Rakefile
CHANGED
|
@@ -2,17 +2,54 @@
|
|
|
2
2
|
|
|
3
3
|
require "bundler/gem_tasks"
|
|
4
4
|
require "rake/testtask"
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
5
|
+
|
|
6
|
+
# Each group runs in its own process: ActiveSupport patches core classes, and
|
|
7
|
+
# test/dummy (integration) defines models that collide with the SQLite ones.
|
|
8
|
+
TEST_GROUPS = {
|
|
9
|
+
core: FileList["test/amount_test.rb", "test/amount/**/*_test.rb"].exclude(
|
|
10
|
+
"test/amount/active_record_test.rb", "test/amount/active_record/**/*"
|
|
11
|
+
),
|
|
12
|
+
active_record: FileList[
|
|
13
|
+
"test/amount/active_record_test.rb", "test/amount/active_record/**/*_test.rb", "test/generators/**/*_test.rb"
|
|
14
|
+
],
|
|
15
|
+
integration: FileList["test/integration/**/*_test.rb"]
|
|
16
|
+
}.freeze
|
|
17
|
+
|
|
18
|
+
namespace :test do
|
|
19
|
+
TEST_GROUPS.each do |group, files|
|
|
20
|
+
Rake::TestTask.new(group) do |task|
|
|
21
|
+
task.libs << "lib" << "test"
|
|
22
|
+
task.test_files = files
|
|
23
|
+
end
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
desc "Run every Minitest group"
|
|
28
|
+
task test: TEST_GROUPS.keys.map { |group| "test:#{group}" }
|
|
29
|
+
|
|
30
|
+
# RuboCop and RSpec are optional bundle groups in CI; define their tasks only
|
|
31
|
+
# when installed.
|
|
32
|
+
begin
|
|
33
|
+
require "rspec/core/rake_task"
|
|
34
|
+
|
|
35
|
+
namespace :spec do
|
|
36
|
+
RSpec::Core::RakeTask.new(:core) { |task| task.pattern = "spec/amount/rspec/**/*_spec.rb" }
|
|
37
|
+
RSpec::Core::RakeTask.new(:active_record) { |task| task.pattern = "spec/amount/active_record/**/*_spec.rb" }
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
desc "Run every RSpec group"
|
|
41
|
+
task spec: %w[spec:core spec:active_record]
|
|
42
|
+
rescue LoadError
|
|
43
|
+
nil
|
|
11
44
|
end
|
|
12
45
|
|
|
13
|
-
|
|
14
|
-
|
|
46
|
+
begin
|
|
47
|
+
require "rubocop/rake_task"
|
|
15
48
|
|
|
16
|
-
|
|
49
|
+
RuboCop::RakeTask.new(:rubocop)
|
|
50
|
+
task lint: %i[rubocop]
|
|
51
|
+
rescue LoadError
|
|
52
|
+
nil
|
|
53
|
+
end
|
|
17
54
|
|
|
18
|
-
task default: %i[test spec
|
|
55
|
+
task default: %i[test spec lint]
|