Class: Money::VariableExchangeBank
- Inherits:
-
Object
- Object
- Money::VariableExchangeBank
- Defined in:
- lib/money/variable_exchange_bank.rb
Constant Summary collapse
- @@singleton =
VariableExchangeBank.new
Class Method Summary collapse
-
.instance ⇒ Object
Returns the singleton instance of VariableExchangeBank.
Instance Method Summary collapse
-
#add_rate(from, to, rate) ⇒ Object
Registers a conversion rate.
-
#exchange(cents, from_currency, to_currency) ⇒ Object
Exchange the given amount of cents in
from_currency
toto_currency
. -
#get_rate(from, to) ⇒ Object
Gets the rate for exchanging the currency named
from
to the currency namedto
. -
#initialize ⇒ VariableExchangeBank
constructor
A new instance of VariableExchangeBank.
-
#same_currency?(currency1, currency2) ⇒ Boolean
Given two currency names, checks whether they’re both the same currency.
Constructor Details
#initialize ⇒ VariableExchangeBank
Returns a new instance of VariableExchangeBank.
29 30 31 32 |
# File 'lib/money/variable_exchange_bank.rb', line 29 def initialize @rates = {} @mutex = Mutex.new end |
Class Method Details
.instance ⇒ Object
Returns the singleton instance of VariableExchangeBank.
By default, Money.default_bank
returns the same object.
25 26 27 |
# File 'lib/money/variable_exchange_bank.rb', line 25 def self.instance @@singleton end |
Instance Method Details
#add_rate(from, to, rate) ⇒ Object
Registers a conversion rate. from
and to
are both currency names.
35 36 37 38 39 |
# File 'lib/money/variable_exchange_bank.rb', line 35 def add_rate(from, to, rate) @mutex.synchronize do @rates["#{from}_TO_#{to}".upcase] = rate end end |
#exchange(cents, from_currency, to_currency) ⇒ Object
Exchange the given amount of cents in from_currency
to to_currency
. Returns the amount of cents in to_currency
as an integer, rounded down.
If the conversion rate is unknown, then Money::UnknownRate will be raised.
62 63 64 65 66 67 68 |
# File 'lib/money/variable_exchange_bank.rb', line 62 def exchange(cents, from_currency, to_currency) rate = get_rate(from_currency, to_currency) if !rate raise Money::UnknownRate, "No conversion rate known for '#{from_currency}' -> '#{to_currency}'" end (cents * rate).floor end |
#get_rate(from, to) ⇒ Object
Gets the rate for exchanging the currency named from
to the currency named to
. Returns nil if the rate is unknown.
43 44 45 46 47 |
# File 'lib/money/variable_exchange_bank.rb', line 43 def get_rate(from, to) @mutex.synchronize do @rates["#{from}_TO_#{to}".upcase] end end |
#same_currency?(currency1, currency2) ⇒ Boolean
Given two currency names, checks whether they’re both the same currency.
bank = VariableExchangeBank.new
bank.same_currency?("usd", "USD") # => true
bank.same_currency?("usd", "EUR") # => false
54 55 56 |
# File 'lib/money/variable_exchange_bank.rb', line 54 def same_currency?(currency1, currency2) currency1.upcase == currency2.upcase end |