Class: ISO4217::Currency::ExchangeBank
- Inherits:
-
Object
- Object
- ISO4217::Currency::ExchangeBank
- Defined in:
- lib/currencies/exchange_bank.rb
Constant Summary collapse
- @@singleton =
ExchangeBank.new
Class Method Summary collapse
Instance Method Summary collapse
- #add_rate(from, to, rate) ⇒ Object
- #exchange(cents, from_currency, to_currency) ⇒ Object
- #get_rate(from, to) ⇒ Object
-
#initialize ⇒ ExchangeBank
constructor
A new instance of ExchangeBank.
- #same_currency?(currency1, currency2) ⇒ Boolean
Constructor Details
#initialize ⇒ ExchangeBank
Returns a new instance of ExchangeBank.
9 10 11 12 |
# File 'lib/currencies/exchange_bank.rb', line 9 def initialize @rates = {} @mutex = Mutex.new end |
Class Method Details
.instance ⇒ Object
5 6 7 |
# File 'lib/currencies/exchange_bank.rb', line 5 def self.instance @@singleton end |
Instance Method Details
#add_rate(from, to, rate) ⇒ Object
14 15 16 17 18 |
# File 'lib/currencies/exchange_bank.rb', line 14 def add_rate(from, to, rate) @mutex.synchronize do @rates["#{from}_TO_#{to}".upcase] = rate end end |
#exchange(cents, from_currency, to_currency) ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/currencies/exchange_bank.rb', line 30 def exchange(cents, from_currency, to_currency) rate = get_rate(from_currency, to_currency) if rate (cents * rate).floor else from_currency = ISO4217::Currency.from_code(from_currency) to_currency = ISO4217::Currency.from_code(to_currency) if from_currency && to_currency && from_currency.exchange_rate && to_currency.exchange_rate && (from_currency.exchange_currency == to_currency.exchange_currency) ((cents * from_currency.exchange_rate) / to_currency.exchange_rate).floor else raise Money::UnknownRate, "No conversion rate known for '#{from_currency}' -> '#{to_currency}'" end end end |
#get_rate(from, to) ⇒ Object
20 21 22 23 24 |
# File 'lib/currencies/exchange_bank.rb', line 20 def get_rate(from, to) @mutex.synchronize do @rates["#{from}_TO_#{to}".upcase] end end |
#same_currency?(currency1, currency2) ⇒ Boolean
26 27 28 |
# File 'lib/currencies/exchange_bank.rb', line 26 def same_currency?(currency1, currency2) currency1.upcase == currency2.upcase end |