Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 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
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,29 @@ t = Transaction.new(amount_cents: 2500, currency: "CAD")
t.amount == Money.new(2500, "CAD") # true
```

#### Assigning Currencies on the go

If you would like to assign different Currency stores(banks) on the go you can use the following method:

`Money.with_bank(bank_of_america)`

This is to allow the usage of custom currency stores to be loaded per User sessions.

An example would be to use the following in a certain controller

```ruby
class ApplicationController
around_action :currency_store
def currency_store
Money.with_bank(Money::Bank::VariableExchange.new(MyCustomStore.new)) do
# Rate will be loaded from the current_user setup.
Money.add_rate("USD", "EUR", 0.5)
yield
end
end
end
```

### Configuration parameters

You can handle a bunch of configuration params through ```money.rb``` initializer:
Expand Down
7 changes: 7 additions & 0 deletions lib/money-rails/money.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ class Money
class << self
alias_method :orig_default_formatting_rules, :default_formatting_rules

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
26 changes: 25 additions & 1 deletion spec/configuration_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,30 @@
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

end