diff --git a/README.md b/README.md index 4765dda93..38c687934 100644 --- a/README.md +++ b/README.md @@ -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: diff --git a/lib/money-rails/money.rb b/lib/money-rails/money.rb index 32ce66db5..c7c35a5df 100644 --- a/lib/money-rails/money.rb +++ b/lib/money-rails/money.rb @@ -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 = { diff --git a/spec/configuration_spec.rb b/spec/configuration_spec.rb index d3f896924..8e22dd7ea 100644 --- a/spec/configuration_spec.rb +++ b/spec/configuration_spec.rb @@ -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 \ No newline at end of file