amounts 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +95 -0
- data/README.md +101 -6
- data/lib/amount/active_record/attribute_definition.rb +12 -8
- data/lib/amount/active_record/calculations.rb +127 -0
- data/lib/amount/active_record/dirty.rb +43 -0
- data/lib/amount/active_record/model.rb +12 -5
- data/lib/amount/active_record/persistence.rb +34 -0
- data/lib/amount/active_record/serialization.rb +57 -0
- data/lib/amount/active_record.rb +6 -0
- data/lib/amount/compact.rb +5 -1
- data/lib/amount/concerns/calculable.rb +4 -1
- data/lib/amount/concerns/exportable.rb +31 -0
- data/lib/amount/concerns/serializable.rb +18 -1
- data/lib/amount/display.rb +7 -4
- data/lib/amount/manifest.rb +128 -0
- data/lib/amount/registry.rb +9 -0
- data/lib/amount/version.rb +1 -1
- data/lib/amount.rb +5 -0
- data/test/amount/active_record/amount_validator_test.rb +8 -0
- data/test/amount/active_record/attribute_definition_test.rb +25 -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/model_test.rb +32 -0
- data/test/amount/active_record/persistence_test.rb +53 -0
- data/test/amount/active_record/serialization_test.rb +75 -0
- data/test/amount/compact_test.rb +22 -7
- data/test/amount/concerns/calculable_test.rb +33 -0
- data/test/amount/concerns/exportable_test.rb +25 -0
- data/test/amount/concerns/serializable_test.rb +42 -4
- data/test/amount/display_test.rb +42 -0
- data/test/amount/manifest_test.rb +325 -0
- data/test/amount/registry_test.rb +14 -0
- data/test/integration/postgresql_test.rb +30 -0
- data/test/support/active_record_test_support.rb +20 -0
- metadata +14 -2
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 1bcdc8db0e926c26c1aa8c46d67056bc9c10a109cf9b9622ca747d4819506173
|
|
4
|
+
data.tar.gz: d3cfb48d0f0d030ca3fa83df0f3a8a0d71bf11b19de5fe2b95870758c273caf2
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 3cd1e9bb7282f1c8e7ca3f3f4c7b4ce431b3fdc818e9e21cb08943e332b9f47456b2388aa931c5ec62b311d94fe767167b0ea421111a72a667611575b407c315
|
|
7
|
+
data.tar.gz: 6ef755ff9eb20f5da1f6ac948598a8a09186c160035adfe480ba93fc26dc314cf2f25fcbe841ecce9cc946a24542bef31f4f6e8b66c30176825cf6db24f3b80e
|
data/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,100 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.0 - 2026-11-15
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- `Amount.manifest(locales: [])` exports the registry as a JSON-ready Hash for
|
|
8
|
+
a client in another language to mirror: every type (with the
|
|
9
|
+
`Amount.register` option names), every default rate as an exact decimal
|
|
10
|
+
string, and for each requested locale every translation the core looks up,
|
|
11
|
+
already resolved. The new `@zarpay/amounts` JavaScript client is built from
|
|
12
|
+
it. Locales need I18n.
|
|
13
|
+
- `Amount::Registry#default_rates` returns every registered default rate,
|
|
14
|
+
keyed by `[from, to]`.
|
|
15
|
+
- `Amount::Compact.locale_format(locale)` is public.
|
|
16
|
+
|
|
17
|
+
### Fixed
|
|
18
|
+
|
|
19
|
+
- **Breaking:** `ui` and `to_s` round negative amounts by magnitude, like
|
|
20
|
+
their positive. `direction: :floor` (the default) now rounds toward zero and
|
|
21
|
+
`:ceil` away from it; before, `:floor` rounded toward negative infinity, so
|
|
22
|
+
a negative displayed more than it was (`-1.234` showed as `$-1.24`, and
|
|
23
|
+
`-0.001` as `$-0.01`). It now shows `$-1.23` and `$0.00`, and a value that
|
|
24
|
+
rounds to zero has no sign. Compact notation follows (`-1_999_999` is
|
|
25
|
+
`-1.99M`, was `-2M`). Positive amounts are unchanged. This matches `*`, `/`,
|
|
26
|
+
`to`, `split` and `allocate`, which already truncate toward zero. Migration:
|
|
27
|
+
code or tests that expect the old output for an inexact negative amount
|
|
28
|
+
should expect its positive's digits; pass `direction: :ceil` for the
|
|
29
|
+
larger magnitude.
|
|
30
|
+
|
|
31
|
+
## 0.2.0 - 2026-11-14
|
|
32
|
+
|
|
33
|
+
### Added
|
|
34
|
+
|
|
35
|
+
- `amount_changes` and `saved_amount_changes` on models with `has_amount`:
|
|
36
|
+
Rails' `changes` and `saved_changes` with each amount by name, as
|
|
37
|
+
`[before, after]` Amounts, in place of its component columns. Rails' own
|
|
38
|
+
change hashes are unchanged.
|
|
39
|
+
- `Model.amount_column_values(attributes)` turns attributes, with amounts by
|
|
40
|
+
name, into column values for `insert_all`, `upsert_all` and their variants,
|
|
41
|
+
which skip attribute writers. Each amount is cast as its writer would cast
|
|
42
|
+
it and replaced by its component columns (all of them even for `nil`, so
|
|
43
|
+
rows share keys); other keys pass through. A fixed-symbol amount in another
|
|
44
|
+
symbol raises `Amount::TypeMismatch`, since bulk writes skip validations.
|
|
45
|
+
- SQL aggregates for `has_amount` attributes that return Amounts:
|
|
46
|
+
`sum_amount`, `minimum_amount`, `maximum_amount` and `average_amount`. Each
|
|
47
|
+
runs one query in the scope of the relation it's called on, so `where`,
|
|
48
|
+
`group` and associations apply. Grouped, the result is keyed like Rails'
|
|
49
|
+
`group(...).sum`. A multi-symbol attribute with more than one symbol in
|
|
50
|
+
scope, or in one group, raises `Amount::TypeMismatch`; group by its symbol
|
|
51
|
+
column for one Amount per symbol. A fixed-symbol sum over no rows is zero;
|
|
52
|
+
other empty results are `nil`. `average_amount` truncates toward zero to a
|
|
53
|
+
whole atomic unit, as `Amount#/` does. Grouping by an association name
|
|
54
|
+
raises `ArgumentError` (group by its foreign key). On SQLite, aggregates
|
|
55
|
+
past 64 bits raise `integer overflow` or come back inexact; PostgreSQL is
|
|
56
|
+
exact.
|
|
57
|
+
|
|
58
|
+
### Changed
|
|
59
|
+
|
|
60
|
+
- **Breaking:** a model with `has_amount` serializes each amount by its name,
|
|
61
|
+
as its exact compact string, in place of its component columns:
|
|
62
|
+
`as_json` gives `"owed" => "USD|10.06"`, not `"owed_atomic" => "1006.0"`
|
|
63
|
+
(`serializable_hash` holds the Amount). `only:` and `except:` take the
|
|
64
|
+
amount's name. `has_amount` includes this into the declaring model;
|
|
65
|
+
`ActiveRecord::Base` and models without amounts are unchanged.
|
|
66
|
+
|
|
67
|
+
Migration: JSON readers that read `<name>_atomic` / `<name>_symbol` read
|
|
68
|
+
`<name>` instead and parse it with `Amount.parse`. Code that needs the raw
|
|
69
|
+
columns reads them from `attributes`
|
|
70
|
+
(`record.attributes.slice("owed_atomic")`).
|
|
71
|
+
- **Breaking:** `Amount#as_json` (and so `to_json`) writes the exact compact
|
|
72
|
+
string: whole units with exactly the symbol's `decimals` places
|
|
73
|
+
(`"USDC|1.500000"`, `"SOL|1.123456789"`). It previously returned `to_s`,
|
|
74
|
+
which rounds down to `ui_decimals`, so JSON silently dropped digits past it
|
|
75
|
+
(`"SOL|1.1234"` for 1.123456789 SOL).
|
|
76
|
+
|
|
77
|
+
Migration: clients that read the value with `Amount.parse` or as a number
|
|
78
|
+
need no change. Where JSON output was compared as a string (tests,
|
|
79
|
+
fixtures) or shown to people, expect the longer form, or use `to_s` or `ui`
|
|
80
|
+
for display.
|
|
81
|
+
|
|
82
|
+
### Fixed
|
|
83
|
+
|
|
84
|
+
- `Amount#/` by a scalar computes the quotient exactly (in `Rational`) before
|
|
85
|
+
truncating it toward zero. It divided in `BigDecimal`, which rounds the
|
|
86
|
+
quotient to a limited precision, so large amounts divided by small decimals
|
|
87
|
+
came out wrong: 10^40 atomic units divided by `BigDecimal("7e-21")` was off
|
|
88
|
+
by 1429 atomic units. Results that were already exact are unchanged.
|
|
89
|
+
`average_amount` divides this way.
|
|
90
|
+
- A subclass of a model with `has_amount` (STI included) inherits its
|
|
91
|
+
parent's amount definitions. It previously started with none, so
|
|
92
|
+
`amount_attribute_definitions`, `amount_atomic_column` and friends raised
|
|
93
|
+
`KeyError` on the subclass, and so did the `amount:` validator and the
|
|
94
|
+
`have_amount_column` matcher for inherited amounts. Amounts a subclass
|
|
95
|
+
declares stay off its parent and siblings. `amount_attribute_definitions`
|
|
96
|
+
is now a `class_attribute` holding a frozen Hash.
|
|
97
|
+
|
|
3
98
|
## 0.1.0 - 2026-11-02
|
|
4
99
|
|
|
5
100
|
### Added
|
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
|
|
@@ -409,6 +413,35 @@ payload = amount.to_h
|
|
|
409
413
|
Amount.load(payload)
|
|
410
414
|
```
|
|
411
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
|
+
|
|
425
|
+
### JavaScript client
|
|
426
|
+
|
|
427
|
+
`Amount.manifest` exports the registry for the
|
|
428
|
+
[`@zarpay/amounts`](../client) JavaScript client, which mirrors the core on the
|
|
429
|
+
web and in React Native: the same parsing, math, conversions, serialization
|
|
430
|
+
and display, on `bigint` atomic values.
|
|
431
|
+
|
|
432
|
+
```ruby
|
|
433
|
+
render json: Amount.manifest(locales: I18n.available_locales)
|
|
434
|
+
```
|
|
435
|
+
|
|
436
|
+
```ts
|
|
437
|
+
const amounts = Amounts.fromManifest(manifest);
|
|
438
|
+
amounts.parse("USDC|1.500000").add(amounts.of("USDC", "0.25")).ui(); // "$1.75"
|
|
439
|
+
```
|
|
440
|
+
|
|
441
|
+
The manifest holds the types (with the `Amount.register` option names), the
|
|
442
|
+
default rates as exact decimal strings, and for each requested locale every
|
|
443
|
+
translation the core looks up. Locales need I18n.
|
|
444
|
+
|
|
412
445
|
## Registry API
|
|
413
446
|
|
|
414
447
|
```ruby
|
|
@@ -416,9 +449,11 @@ Amount.register(...)
|
|
|
416
449
|
Amount.register_default_rate(:USD, :USDC, "1")
|
|
417
450
|
Amount.registry.lookup(:USDC)
|
|
418
451
|
Amount.registry.symbols
|
|
452
|
+
Amount.registry.default_rates
|
|
419
453
|
Amount.registry.clear!
|
|
420
454
|
Amount.registry.lock!
|
|
421
455
|
Amount.registry.locked?
|
|
456
|
+
Amount.manifest(locales: %i[en de])
|
|
422
457
|
```
|
|
423
458
|
|
|
424
459
|
## ActiveRecord Integration
|
|
@@ -482,6 +517,34 @@ Writers accept:
|
|
|
482
517
|
- `Hash` payloads
|
|
483
518
|
- raw numeric values for fixed-symbol attributes only
|
|
484
519
|
|
|
520
|
+
A subclass (STI included) inherits its parent's amounts. Amounts it declares
|
|
521
|
+
itself stay off the parent and its other subclasses.
|
|
522
|
+
|
|
523
|
+
`as_json`, `to_json` and `serializable_hash` write each amount by its name, as
|
|
524
|
+
its exact compact string, in place of its columns. `only:` and `except:` take the
|
|
525
|
+
amount's name, and the raw columns stay readable through `attributes`.
|
|
526
|
+
`amount_changes` and `saved_amount_changes` are `changes` and `saved_changes`
|
|
527
|
+
with amounts by name. Rails' own change hashes stay keyed by column:
|
|
528
|
+
|
|
529
|
+
```ruby
|
|
530
|
+
holding.as_json # => { "id" => 1, "amount" => "USDC|1.500000", "fee" => "SOL|0.250000000" }
|
|
531
|
+
|
|
532
|
+
holding.update!(amount: "USDC|2")
|
|
533
|
+
holding.saved_amount_changes # => { "amount" => [#<Amount USDC $1.50>, #<Amount USDC $2.00>] }
|
|
534
|
+
```
|
|
535
|
+
|
|
536
|
+
`insert_all` and `upsert_all` skip writers, so `amount_column_values` turns
|
|
537
|
+
amounts by name into their columns first. It casts like the writer, raises
|
|
538
|
+
`Amount::TypeMismatch` for a fixed-symbol amount in another symbol, and gives
|
|
539
|
+
every column of a `nil` amount so rows share keys:
|
|
540
|
+
|
|
541
|
+
```ruby
|
|
542
|
+
Holding.amount_column_values(amount: "USDC|1.50", fee: 0.25)
|
|
543
|
+
# => { "amount_atomic" => 1500000, "amount_symbol" => "USDC", "fee_atomic" => 250000000 }
|
|
544
|
+
|
|
545
|
+
Holding.insert_all(rows.map { |row| Holding.amount_column_values(row) })
|
|
546
|
+
```
|
|
547
|
+
|
|
485
548
|
Scopes:
|
|
486
549
|
|
|
487
550
|
```ruby
|
|
@@ -494,6 +557,23 @@ Holding.where_amount_between("USDC|1.00", "USDC|5.00")
|
|
|
494
557
|
Holding.amount_in(:USDC)
|
|
495
558
|
```
|
|
496
559
|
|
|
560
|
+
Aggregates run in SQL and return Amounts, one query each, in the scope they're
|
|
561
|
+
called on (`where`, `group` and associations apply):
|
|
562
|
+
|
|
563
|
+
```ruby
|
|
564
|
+
Holding.sum_amount(:fee) # => #<Amount SOL ...>
|
|
565
|
+
Holding.minimum_amount(:fee)
|
|
566
|
+
Holding.maximum_amount(:fee)
|
|
567
|
+
Holding.average_amount(:fee) # truncated toward zero, like Amount#/
|
|
568
|
+
Holding.group(:amount_symbol).sum_amount(:amount) # => { "USDC" => #<Amount USDC ...>, "SOL" => ... }
|
|
569
|
+
```
|
|
570
|
+
|
|
571
|
+
Symbols never mix: a multi-symbol attribute with more than one symbol in scope
|
|
572
|
+
(or in one group) raises `Amount::TypeMismatch`, so group by its symbol column for
|
|
573
|
+
one Amount per symbol. A fixed-symbol sum over no rows is zero; otherwise an
|
|
574
|
+
empty set gives `nil`. Group by a column or SQL expression, not an association
|
|
575
|
+
name.
|
|
576
|
+
|
|
497
577
|
Suggested check constraint for multi-symbol amounts:
|
|
498
578
|
|
|
499
579
|
```sql
|
|
@@ -532,7 +612,7 @@ for free.
|
|
|
532
612
|
|
|
533
613
|
### SQLite Note
|
|
534
614
|
|
|
535
|
-
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.
|
|
615
|
+
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.
|
|
536
616
|
|
|
537
617
|
### PostgreSQL Dummy App
|
|
538
618
|
|
|
@@ -596,14 +676,20 @@ bundle exec rspec
|
|
|
596
676
|
|
|
597
677
|
## Releases
|
|
598
678
|
|
|
599
|
-
|
|
679
|
+
The gem and the [`@zarpay/amounts`](../client) JavaScript client are versioned in lockstep and
|
|
680
|
+
released together from one GitHub Release, both through trusted publishing.
|
|
600
681
|
|
|
601
682
|
Workflow:
|
|
602
683
|
|
|
603
|
-
-
|
|
684
|
+
- bump `Amount::VERSION` and `client/package.json` to the same version (CI fails when they
|
|
685
|
+
differ), and date both changelogs
|
|
686
|
+
- create and push a version tag such as `v0.3.0`
|
|
604
687
|
- publish a GitHub Release for that tag
|
|
605
|
-
- GitHub Actions runs `.github/workflows/release.yml
|
|
606
|
-
|
|
688
|
+
- GitHub Actions runs `.github/workflows/release.yml`, which verifies the test suite and
|
|
689
|
+
publishes the gem to RubyGems.org
|
|
690
|
+
- and `.github/workflows/publish-npm.yml`, which verifies the tag against both versions, runs
|
|
691
|
+
the client's checks and publishes `@zarpay/amounts` to npm with provenance (skipping a
|
|
692
|
+
version that's already on npm)
|
|
607
693
|
|
|
608
694
|
RubyGems setup:
|
|
609
695
|
|
|
@@ -613,9 +699,18 @@ RubyGems setup:
|
|
|
613
699
|
- workflow filename: `release.yml`
|
|
614
700
|
- GitHub Actions environment: `release`
|
|
615
701
|
|
|
616
|
-
|
|
702
|
+
npm setup:
|
|
703
|
+
|
|
704
|
+
- the first version of `@zarpay/amounts` is published once by hand (`npm publish --access public`
|
|
705
|
+
from `client/`), since npm can only attach a trusted publisher to a package that exists
|
|
706
|
+
- on npmjs.com, in the package's settings, add a trusted publisher: GitHub Actions, organization
|
|
707
|
+
`zarpay`, repository `amounts`, workflow filename `publish-npm.yml`, environment `release`
|
|
708
|
+
|
|
709
|
+
This uses OIDC trusted publishing on both registries, so no API token needs to be stored in
|
|
710
|
+
GitHub Actions. See the official guides:
|
|
617
711
|
|
|
618
712
|
- https://guides.rubygems.org/trusted-publishing/
|
|
713
|
+
- https://docs.npmjs.com/trusted-publishers
|
|
619
714
|
|
|
620
715
|
## Compared to `money`
|
|
621
716
|
|
|
@@ -35,17 +35,21 @@ class Amount
|
|
|
35
35
|
end
|
|
36
36
|
|
|
37
37
|
def write(record, value)
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
return nil
|
|
42
|
-
end
|
|
38
|
+
column_values(value).each { |column, column_value| record.write_attribute(column, column_value) }
|
|
39
|
+
value
|
|
40
|
+
end
|
|
43
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)
|
|
44
48
|
# The Integer itself, not its string: Rails 8.1 cuts a String cast to an
|
|
45
49
|
# integer column to 16 bytes, which silently truncates large values.
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
50
|
+
values = { atomic_column => value&.atomic }
|
|
51
|
+
values[symbol_column] = value&.symbol&.to_s unless fixed_symbol?
|
|
52
|
+
values
|
|
49
53
|
end
|
|
50
54
|
|
|
51
55
|
def build_from_values(values)
|
|
@@ -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
|
|
@@ -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
|
|
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)
|
|
@@ -24,10 +35,6 @@ class Amount
|
|
|
24
35
|
@model_name ||= ::ActiveModel::Name.new(self, nil, "AnonymousModel")
|
|
25
36
|
end
|
|
26
37
|
|
|
27
|
-
def amount_attribute_definitions
|
|
28
|
-
@amount_attribute_definitions ||= {}
|
|
29
|
-
end
|
|
30
|
-
|
|
31
38
|
def amount_component_columns(name)
|
|
32
39
|
amount_attribute_definition(name).component_columns
|
|
33
40
|
end
|
|
@@ -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
|
data/lib/amount/active_record.rb
CHANGED
|
@@ -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.
|
|
@@ -47,6 +51,8 @@ class Amount
|
|
|
47
51
|
end
|
|
48
52
|
|
|
49
53
|
::ActiveRecord::Base.extend(Model)
|
|
54
|
+
::ActiveRecord::Base.extend(Calculations)
|
|
55
|
+
::ActiveRecord::Base.extend(Persistence)
|
|
50
56
|
::ActiveRecord::Base.include(InstanceMethods)
|
|
51
57
|
end
|
|
52
58
|
end
|
data/lib/amount/compact.rb
CHANGED
|
@@ -117,6 +117,10 @@ class Amount
|
|
|
117
117
|
Formattable.fill(locale_format(locale), number:, label: word)
|
|
118
118
|
end
|
|
119
119
|
|
|
120
|
+
# The template joining a compacted number and its scale word in `locale`:
|
|
121
|
+
# `number.human.decimal_units.format` when it places `%n`, else `"%n %u"`.
|
|
122
|
+
# @param locale [Symbol, String]
|
|
123
|
+
# @return [String]
|
|
120
124
|
def locale_format(locale)
|
|
121
125
|
found = Locale.translate(LOCALE_FORMAT_KEY, locale, LOCALE_FORMAT)
|
|
122
126
|
Formattable.valid_template?(found) ? found : LOCALE_FORMAT
|
|
@@ -132,6 +136,6 @@ class Amount
|
|
|
132
136
|
raise ArgumentError, "compact: precision must be a positive Integer, got #{digits.inspect}"
|
|
133
137
|
end
|
|
134
138
|
|
|
135
|
-
private_class_method :round, :number, :join, :
|
|
139
|
+
private_class_method :round, :number, :join, :precision_from_hash
|
|
136
140
|
end
|
|
137
141
|
end
|
|
@@ -75,7 +75,10 @@ class Amount
|
|
|
75
75
|
ensure_scalar!(other)
|
|
76
76
|
raise ZeroDivisionError if other.zero?
|
|
77
77
|
|
|
78
|
-
|
|
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
|
|