Skip to content

Commit

Permalink
Raise error when trying to change model based currency
Browse files Browse the repository at this point in the history
  • Loading branch information
dapi committed Dec 2, 2013
1 parent 468b3aa commit 93682fe
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
@@ -1,6 +1,7 @@
# Changelog

## master (next release)
- Raise error when trying to change model based currency
- Add testing tasks for rails 4.x
- Fix issue with Numeric values in MoneyValidator (GH-83).
- Fix test helper
Expand Down
1 change: 1 addition & 0 deletions CONTRIBUTORS
Expand Up @@ -11,6 +11,7 @@ Carlos Hernandez
Carlos Hernández
Clarke Brunsdon
Dan Beaulieu
Danil Pismenny
Deepak Kannan
Derek Bender
Dmitriy Dudkin
Expand Down
11 changes: 11 additions & 0 deletions lib/money-rails/active_record/monetizable.rb
Expand Up @@ -150,6 +150,17 @@ def monetized_attributes
# Update cents
send("#{subunit_name}=", money.try(:cents))

money_currency = money.try(:currency)

if self.respond_to?("#{instance_currency_name}=")
send("#{instance_currency_name}=", money_currency.try(:iso_code))
else
current_currency = send("currency_for_#{name}")
if money_currency && current_currency != money_currency
raise "Can't change readonly currency '#{current_currency}' to '#{money_currency}' for field '#{name}'"
end
end

# Update currency iso value if there is an instance currency attribute
if instance_currency_name.present? &&
self.respond_to?("#{instance_currency_name}=")
Expand Down
26 changes: 26 additions & 0 deletions spec/active_record/monetizable_spec.rb
Expand Up @@ -47,6 +47,13 @@ class Sub < Product; end
product.price_cents.should == 215
end

it "should raise error if can't change currency" do
product = Product.new
expect {
product.price Money.new(10,'RUB')
}.to raise_error
end

it "respects :as argument" do
product.discount_value.should == Money.new(150, "USD")
end
Expand Down Expand Up @@ -389,11 +396,30 @@ class Sub < Product; end
product = Product.create(:sale_price_amount => 1234)
product.sale_price.currency_as_string == 'USD'
end

it "is overridden by instance currency column" do
product = Product.create(:sale_price_amount => 1234,
:sale_price_currency_code => 'CAD')
product.sale_price.currency_as_string.should == 'CAD'
end

it 'can change currency of custom column' do
product = Product.create!(
:price => Money.new(10,'USD'),
:bonus => Money.new(10,'GBP'),
:discount => 10,
:sale_price_amount => 1234,
:sale_price_currency_code => 'USD')

product.sale_price.currency_as_string.should == 'USD'

product.sale_price = Money.new 456, 'CAD'
product.save
product.reload

product.sale_price.currency_as_string.should == 'CAD'
product.discount_value.currency_as_string.should == 'USD'
end
end

context "for model with currency column:" do
Expand Down

0 comments on commit 93682fe

Please sign in to comment.