Skip to content

Commit

Permalink
Ignore converted methods when writing cents
Browse files Browse the repository at this point in the history
  • Loading branch information
edithemmings committed Oct 11, 2024
1 parent df7a030 commit 2ca99c0
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 5 deletions.
2 changes: 1 addition & 1 deletion Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ platforms :jruby do
end

platforms :ruby do
gem "sqlite3"
gem "sqlite3", "~> 1.4"
end

platform :mri do
Expand Down
15 changes: 11 additions & 4 deletions lib/money-rails/active_record/monetizable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def monetize(*fields)
# the subunit value directly
define_method "#{subunit_name}=" do |value|
instance_variable_set "@#{name}_money_before_type_cast", nil
write_attribute(subunit_name, value)
write_cents(subunit_name, value)
end
end

Expand Down Expand Up @@ -205,7 +205,7 @@ def read_monetized(name, subunit_name, options = nil, *args, **kwargs)
result = memoized
else
memoized_amount = memoized.amount.to_money(attr_currency)
write_attribute subunit_name, memoized_amount.cents
write_cents subunit_name, memoized_amount.cents
# Cache the value (it may be nil)
result = instance_variable_set("@#{name}", memoized_amount)
end
Expand Down Expand Up @@ -262,9 +262,9 @@ def write_monetized(name, subunit_name, value, validation_enabled, instance_curr
# (Note: 'attribute_aliases' doesn't exist in Rails 3.x, so we
# can't tell if the attribute was aliased.)
original_name = self.class.attribute_aliases[subunit_name.to_s]
write_attribute(original_name, money.try(:cents))
write_cents(original_name, money.try(:cents))
else
write_attribute(subunit_name, money.try(:cents))
write_cents(subunit_name, money.try(:cents))
end

if money_currency = money.try(:currency)
Expand Down Expand Up @@ -299,6 +299,13 @@ def currency_for(name, instance_currency_name, field_currency_name)
Money.default_currency
end
end

def write_cents(attribute_name, cents)
# ignore converted methods
return unless has_attribute? attribute_name

write_attribute(attribute_name, cents)
end
end
end
end
8 changes: 8 additions & 0 deletions spec/active_record/monetizable_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,14 @@ def assert_monetized_attributes(monetized_attributes, expected_attributes)
expect(transaction.amount_cents).to eq(20000)
end

it "update to instance currency field gets applied to converted methods" do
transaction = Transaction.create(amount: '200', tax: '10', currency: 'USD')
expect(transaction.total).to eq(Money.new(21000, 'USD'))

transaction.currency = 'CAD'
expect(transaction.total).to eq(Money.new(21000, 'CAD'))
end

it "raises an error if trying to create two attributes with the same name" do
expect do
class Product
Expand Down

0 comments on commit 2ca99c0

Please sign in to comment.