Skip to content

Commit

Permalink
add optional currency argument to String#to_money
Browse files Browse the repository at this point in the history
  • Loading branch information
semmons99 committed Jul 9, 2010
1 parent bad6f51 commit 04fcbd2
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
17 changes: 15 additions & 2 deletions lib/money/core_extensions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions test/core_extensions_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 04fcbd2

Please sign in to comment.