Skip to content

Commit

Permalink
Add Money.with_rounding_mode as a replacement for Money.roudning_mode…
Browse files Browse the repository at this point in the history
… with a block (tonsky#850)
  • Loading branch information
antstorm authored Mar 2, 2019
1 parent 422172a commit faa0323
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 18 deletions.
38 changes: 21 additions & 17 deletions lib/money/money.rb
Original file line number Diff line number Diff line change
Expand Up @@ -186,32 +186,36 @@ def self.inherited(base)

setup_defaults

# Use this to return the rounding mode. You may also pass a
# rounding mode and a block to temporarily change it. It will
# then return the results of the block instead.
# Use this to return the rounding mode.
#
# @param [BigDecimal::ROUND_MODE] mode
#
# @return [BigDecimal::ROUND_MODE,Yield] rounding mode or block results
# @return [BigDecimal::ROUND_MODE] rounding mode
def self.rounding_mode(mode = nil)
return Thread.current[:money_rounding_mode] || @rounding_mode unless mode

warn "[DEPRECATION] calling `rounding_mode` with a block is deprecated. Please use `.with_rounding_mode` instead."
with_rounding_mode(mode) { yield }
end

# This method temporarily changes the rounding mode. It will then return the
# results of the block instead.
#
# @param [BigDecimal::ROUND_MODE] mode
#
# @return [BigDecimal::ROUND_MODE,Yield] block results
#
# @example
# fee = Money.rounding_mode(BigDecimal::ROUND_HALF_UP) do
# fee = Money.with_rounding_mode(BigDecimal::ROUND_HALF_UP) do
# Money.new(1200) * BigDecimal('0.029')
# end
def self.rounding_mode(mode = nil)
if mode.nil?
Thread.current[:money_rounding_mode] || @rounding_mode
else
begin
Thread.current[:money_rounding_mode] = mode
yield
ensure
Thread.current[:money_rounding_mode] = nil
end
end
def self.with_rounding_mode(mode)
Thread.current[:money_rounding_mode] = mode
yield
ensure
Thread.current[:money_rounding_mode] = nil
end


# Adds a new exchange rate to the default bank and return the rate.
#
# @param [Currency, String, Symbol] from_currency Currency to exchange from.
Expand Down
10 changes: 9 additions & 1 deletion spec/money_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -193,13 +193,21 @@
expect(Money.from_amount(1, "USD", bank).bank).to eq bank
end

it 'rounds using rounding_mode' do
it 'warns about rounding_mode deprecation' do
expect(Money).to receive(:warn)
expect(Money.from_amount(1.999).to_d).to eq 2
expect(Money.rounding_mode(BigDecimal::ROUND_DOWN) do
Money.from_amount(1.999).to_d
end).to eq 1.99
end

it 'rounds using with_rounding_mode' do
expect(Money.from_amount(1.999).to_d).to eq 2
expect(Money.with_rounding_mode(BigDecimal::ROUND_DOWN) do
Money.from_amount(1.999).to_d
end).to eq 1.99
end

context 'given a currency is provided' do
context 'and the currency is nil' do
let(:currency) { nil }
Expand Down

0 comments on commit faa0323

Please sign in to comment.