Skip to content
Browse files

add optional currency argument to String#to_money

  • Loading branch information...
1 parent bad6f51 commit 04fcbd29ee4c6d41a40af064575d70ec6d93b2c3 @semmons99 semmons99 committed Jul 9, 2010
Showing with 22 additions and 2 deletions.
  1. +15 −2 lib/money/core_extensions.rb
  2. +7 −0 test/core_extensions_spec.rb
View
17 lib/money/core_extensions.rb
@@ -22,10 +22,23 @@ class String
# 'USD 100'.to_money # => #<Money @cents=10000, @currency="USD">
# '$100 USD'.to_money # => #<Money @cents=10000, @currency="USD">
# 'hello 2000 world'.to_money # => #<Money @cents=200000 @currency="USD")>
- def to_money
+ def to_money(currency = nil)
# Get the currency.
matches = scan /([A-Z]{2,3})/
- currency = matches[0] ? matches[0][0] : Money.default_currency
+ _currency_ = matches[0] ? matches[0][0] : nil
+
+ # check that currency passed and embedded currency are the same, or only
+ # one or the other is present.
+ if currency.nil? and _currency_.nil?
+ currency = Money.default_currency
+ elsif currency.nil?
+ currency = _currency_
+ elsif _currency_.nil?
+ currency = currency
+ elsif currency != _currency_
+ raise "mismatching currencies"
+ end
+
cents = calculate_cents(self)
Money.new(cents, currency)
end
View
7 test/core_extensions_spec.rb
@@ -78,6 +78,13 @@
"$1.99000 USD".to_money.should == Money.new(1_99, "USD")
end
+ specify "String#to_money should accept optional currency" do
+ "10.10".to_money('USD').should == Money.new(1010, 'USD')
+ "10.10".to_money('EUR').should == Money.new(1010, 'EUR')
+ "10.10 USD".to_money('USD').should == Money.new(1010, 'USD')
+ lambda{"10.10 USD".to_money('EUR')}.should raise_error
+ end
+
specify "String#to_money ignores unrecognized data" do
"hello 2000 world".to_money.should == Money.new(2000_00)
end

0 comments on commit 04fcbd2

Please sign in to comment.
Something went wrong with that request. Please try again.