Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions lib/money-rails/money.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,19 @@ class Money
class << self
alias_method :orig_default_formatting_rules, :default_formatting_rules

# Temporarily sets the default bank for Money operations within the block
#
# @param bank [Money::Bank] the bank to use temporarily
# @yield the block to execute with the temporary bank
# @return [Object] the return value of the yielded block
#
def with_bank(bank)
old_bank, ::Money.default_bank = ::Money.default_bank, bank
yield
ensure
::Money.default_bank = old_bank
end

def default_formatting_rules
rules = orig_default_formatting_rules || {}
defaults = {
Expand Down
23 changes: 23 additions & 0 deletions spec/configuration_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,29 @@
end
end
end
end

describe 'modifying default bank from memory' do
it 'creates new banks when needed' do
old_bank = Money.default_bank

bank = Money::Bank::VariableExchange.new

Money.with_bank(bank) {}
expect(Money.default_bank).to eq(old_bank)
end

it "uses the correct bank inside block" do
old_bank = Money.default_bank
custom_store = double
bank = Money::Bank::VariableExchange.new(custom_store)
Money.with_bank(bank) do
expect(custom_store).to receive(:add_rate).with("USD", "EUR", 0.5).once
Money.add_rate("USD", "EUR", 0.5)
end

expect(old_bank).to receive(:add_rate)
Money.add_rate("USD", "EUR", 0.5)
end
end
end