Class: ExchangeRate::CurrencyConverter

Inherits:
Object
  • Object
show all
Defined in:
lib/exchange_rate/currency_converter.rb

Overview

Convert between currencies, using the local cache store

Examples

CurrencyConverter.new(Date.today, 'GBP', 'USD').convert!
# => 1.291700027

Instance Method Summary collapse

Constructor Details

#initialize(date_of_rate, source_currency, target_currency) ⇒ CurrencyConverter

Builds a CurrencyConverter. The cache is not accessed on initialization.

date_of_rate - The date the rate should be used, for historical conversions. source_currency - The source currency code, e.g. ‘GBP’. target_currency - The target currency code, e.g. ‘USD’.



19
20
21
22
23
# File 'lib/exchange_rate/currency_converter.rb', line 19

def initialize(date_of_rate, source_currency, target_currency)
  @date_of_rate = date_of_rate
  @source_currency = source_currency
  @target_currency = target_currency
end

Instance Method Details

#convert!(source_value: 1) ⇒ Object

Convert between the source and target currencies. By default this will take 1 unit of the source currency.

source_value - The number of units of source currency to convert.

Examples

converter = CurrencyConverter.new(Date.today, 'GBP', 'USD')

converter.convert
# => 1.291700027

converter.convert(source_value: 2)
# => 2.583400054


41
42
43
# File 'lib/exchange_rate/currency_converter.rb', line 41

def convert!(source_value: 1)
  (source_value / source_rate) * target_rate
end

#source_rateObject

The (cached) source ExchangeRate::CurrencyRate object.

Returns ExchangeRate::CurrencyRate.

Raises ExchangeRate::MissingRateError if a cached rate does not exist.



51
52
53
# File 'lib/exchange_rate/currency_converter.rb', line 51

def source_rate
  find_currency_rate(@source_currency, @date_of_rate).value_in_euro
end

#target_rateObject

The (cached) source ExchangeRate::CurrencyRate object.

Returns ExchangeRate::CurrencyRate.

Raises ExchangeRate::MissingRateError if a cached rate does not exist.



61
62
63
# File 'lib/exchange_rate/currency_converter.rb', line 61

def target_rate
  find_currency_rate(@target_currency, @date_of_rate).value_in_euro
end