Last active
April 3, 2018 16:34
-
-
Save yevgenko/4dc3752facef962ee2aa4c2d672d5213 to your computer and use it in GitHub Desktop.
Forcing monetization to produce money in specific currency only
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'money' | |
class BigMoney | |
class << self | |
attr_accessor :current_currency | |
def force_currency(currency_code) | |
self.current_currency = Money::Currency.new(currency_code) | |
yield | |
self.current_currency = nil | |
end | |
def monetize(amount:, currency_code:) | |
money = Money.from_amount(amount, currency_code) | |
return money unless self.current_currency | |
money.exchange_to self.current_currency | |
end | |
end | |
end | |
describe BigMoney do | |
describe '.force_currency' do | |
it 'forces monetization to produce money in specific currency only' do | |
Money.default_bank.add_rate('GBP', 'USD', 2) | |
GBP = { amount: 5, currency_code: 'GBP' } | |
USD = { amount: 10, currency_code: 'USD' } | |
USD_money = described_class.monetize(USD) | |
expect(described_class.monetize(GBP)).not_to eq USD_money | |
described_class.force_currency('USD') do | |
expect(described_class.monetize(GBP)).to eq USD_money | |
end | |
expect(described_class.monetize(GBP)).not_to eq USD_money | |
## | |
# Sample: mapping order entity to CSV with two currencies | |
## | |
class Order | |
attr_reader :currency_code | |
def initialize(currency_code) | |
@subtotal = 10 | |
@total_tax = 0 | |
@total = 10 | |
@currency_code = currency_code | |
end | |
def subtotal | |
monetize(@subtotal) | |
end | |
def total_tax | |
monetize(@total_tax) | |
end | |
def total | |
monetize(@total) | |
end | |
private | |
def monetize(amount) | |
BigMoney.monetize(amount: amount, currency_code: currency_code) | |
end | |
end | |
order = Order.new('GBP') | |
totals_csv = { | |
subtotal: order.subtotal, | |
total_tax: order.total_tax, | |
total: order.total | |
} | |
BigMoney.force_currency('USD') do | |
totals_csv.merge!({ | |
subtotal_usd: order.subtotal, | |
total_tax_usd: order.total_tax, | |
total_usd: order.total | |
}) | |
end | |
pp totals_csv | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment