Skip to content
Browse files

if currency responds to :cents_in_whole, use it!

  • Loading branch information...
1 parent 5a7cad4 commit a27138fd3d2cb10eae894be37cb3426371440392 @semmons99 committed
Showing with 26 additions and 2 deletions.
  1. +12 −0 README.md
  2. +6 −2 lib/cashrb/cash.rb
  3. +8 −0 test/test_cash.rb
View
12 README.md
@@ -58,3 +58,15 @@ Usage
n = Cash.new(1.9)
n.cents #=> 1
+
+ # If your currency object implements :cents_in_whole, we'll go ahead and
+ # use that.
+
+ module MyCurrency
+ def self.cents_in_whole
+ 10
+ end
+ end
+
+ n = Cash.new(9, :currency => MyCurrency)
+ n.to_f #=> 0.9
View
8 lib/cashrb/cash.rb
@@ -118,10 +118,14 @@ def parse_initialize_options(options)
:currency => self.class.default_currency,
}.merge(options)
- @cents_in_whole = opts[:cents_in_whole]
+ @currency = opts[:currency]
+ @cents_in_whole = if @currency.respond_to? :cents_in_whole
+ @currency.cents_in_whole
+ else
+ opts[:cents_in_whole]
+ end
@decimal_places = decimal_places(@cents_in_whole)
@rounding_method = opts[:rounding_method]
- @currency = opts[:currency]
nil
end
View
8 test/test_cash.rb
@@ -50,6 +50,14 @@ def test_new_with_currency
assert_equal :usd, rs.currency
end
+ def test_new_with_currency_respond_to_cents_in_whole
+ currency = MiniTest::Mock.new
+ currency.expect(:cents_in_whole, 10)
+
+ rs = Cash.new(9, :currency => currency)
+ assert_equal 0.9, rs.to_f
+ end
+
def test_plus_with_Cash_Cash
rs = Cash.new(6) + Cash.new(4)
assert_equal Cash.new(10), rs

0 comments on commit a27138f

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