Skip to content

Commit b923185

Browse files
committed
Skip subunit write for non-attributes on currency change in getter
1 parent df7a030 commit b923185

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

lib/money-rails/active_record/monetizable.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ def read_monetized(name, subunit_name, options = nil, *args, **kwargs)
205205
result = memoized
206206
else
207207
memoized_amount = memoized.amount.to_money(attr_currency)
208-
write_attribute subunit_name, memoized_amount.cents
208+
write_attribute subunit_name, memoized_amount.cents if has_attribute? subunit_name
209209
# Cache the value (it may be nil)
210210
result = instance_variable_set("@#{name}", memoized_amount)
211211
end

spec/active_record/monetizable_spec.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,14 @@ def assert_monetized_attributes(monetized_attributes, expected_attributes)
105105
expect(transaction.amount_cents).to eq(20000)
106106
end
107107

108+
it "update to instance currency field gets applied to converted methods" do
109+
transaction = Transaction.create(amount: '200', tax: '10', currency: 'USD')
110+
expect(transaction.total).to eq(Money.new(21000, 'USD'))
111+
112+
transaction.currency = 'CLP'
113+
expect(transaction.total).to eq(Money.new(210, 'CLP'))
114+
end
115+
108116
it "raises an error if trying to create two attributes with the same name" do
109117
expect do
110118
class Product

0 commit comments

Comments
 (0)