Class: DailyExchangeRatesBank

Inherits:
Money::Bank::VariableExchange
  • Object
show all
Defined in:
lib/daily_exchange_rates_bank.rb,
lib/daily_exchange_rates_bank/exchange_rates_api_client.rb

Overview

Class for aiding in exchanging money between different currencies.

Defined Under Namespace

Classes: ExchangeRatesApiClient

Constant Summary collapse

SERIALIZER_DATE_SEPARATOR =
'_ON_'

Instance Method Summary collapse

Constructor Details

#initialize(store = Money::RatesStore::StoreWithDateSupport.new, &block) ⇒ DailyExchangeRatesBank

Returns a new instance of DailyExchangeRatesBank.



11
12
13
# File 'lib/daily_exchange_rates_bank.rb', line 11

def initialize(store = Money::RatesStore::StoreWithDateSupport.new, &block)
  super(store, &block)
end

Instance Method Details

#exchange(cents, from_currency, to_currency, date = nil) ⇒ Object



36
37
38
# File 'lib/daily_exchange_rates_bank.rb', line 36

def exchange(cents, from_currency, to_currency, date = nil)
  exchange_with(Money.new(cents, from_currency), to_currency, date)
end

#exchange_with(from, to_currency, date = nil) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/daily_exchange_rates_bank.rb', line 40

def exchange_with(from, to_currency, date = nil)
  to_currency = ::Money::Currency.wrap(to_currency)
  return from if from.currency == to_currency

  rate = get_rate(from.currency, to_currency, date)

  rate ||= rate_from_exchange_rates_api(from.currency, to_currency, date)

  fractional = calculate_fractional(from, to_currency, rate)
  Money.new(fractional, to_currency)
end

#get_rate(from, to, date = nil) ⇒ Object



15
16
17
18
19
# File 'lib/daily_exchange_rates_bank.rb', line 15

def get_rate(from, to, date = nil)
  store.get_rate(::Money::Currency.wrap(from).iso_code,
                 ::Money::Currency.wrap(to).iso_code,
                 date)
end

#ratesObject



28
29
30
31
32
33
34
# File 'lib/daily_exchange_rates_bank.rb', line 28

def rates
  store.each_rate.each_with_object({}) do |(from, to, rate, date), hash|
    key = [from, to].join(SERIALIZER_SEPARATOR)
    key = [key, date.to_s].join(SERIALIZER_DATE_SEPARATOR) if date
    hash[key] = rate
  end
end

#set_rate(from, to, rate, date = nil) ⇒ Object



21
22
23
24
25
26
# File 'lib/daily_exchange_rates_bank.rb', line 21

def set_rate(from, to, rate, date = nil)
  store.add_rate(::Money::Currency.wrap(from).iso_code,
                 ::Money::Currency.wrap(to).iso_code,
                 rate,
                 date)
end