Class: ExchangeRate::CurrencyConverter
- Inherits:
-
Object
- Object
- ExchangeRate::CurrencyConverter
- Defined in:
- lib/exchange_rate/currency_converter.rb
Overview
Instance Method Summary collapse
-
#convert!(source_value: 1) ⇒ Object
Convert between the source and target currencies.
-
#initialize(date_of_rate, source_currency, target_currency) ⇒ CurrencyConverter
constructor
Builds a CurrencyConverter.
-
#source_rate ⇒ Object
The (cached) source ExchangeRate::CurrencyRate object.
-
#target_rate ⇒ Object
The (cached) source ExchangeRate::CurrencyRate object.
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_rate ⇒ Object
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_rate ⇒ Object
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 |