Class: Money::RatesStore::Memory
- Inherits:
-
Object
- Object
- Money::RatesStore::Memory
- Defined in:
- lib/money/rates_store/memory.rb
Overview
Class for thread-safe storage of exchange rate pairs. Used by instances of Money::Bank::VariableExchange.
Constant Summary collapse
- INDEX_KEY_SEPARATOR =
'_TO_'.freeze
Instance Method Summary collapse
-
#add_rate(currency_iso_from, currency_iso_to, rate) ⇒ Numeric
Registers a conversion rate and returns it.
-
#each_rate {|iso_from, iso_to, rate| ... } ⇒ Enumerator
Iterate over rate tuples (iso_from, iso_to, rate).
-
#get_rate(currency_iso_from, currency_iso_to) ⇒ Numeric
Retrieve the rate for the given currencies.
-
#initialize(opts = {}, rt = {}) ⇒ Memory
constructor
Initializes a new
Money::RatesStore::Memoryobject. - #marshal_dump ⇒ Object
-
#transaction(&block) ⇒ Object
Wraps block execution in a thread-safe transaction.
Constructor Details
#initialize(opts = {}, rt = {}) ⇒ Memory
Initializes a new Money::RatesStore::Memory object.
21 22 23 24 25 |
# File 'lib/money/rates_store/memory.rb', line 21 def initialize(opts = {}, rt = {}) @options, @index = opts, rt @mutex = Mutex.new @in_transaction = false end |
Instance Method Details
#add_rate(currency_iso_from, currency_iso_to, rate) ⇒ Numeric
Registers a conversion rate and returns it. Uses Mutex to synchronize data access.
39 40 41 |
# File 'lib/money/rates_store/memory.rb', line 39 def add_rate(currency_iso_from, currency_iso_to, rate) transaction { index[rate_key_for(currency_iso_from, currency_iso_to)] = rate } end |
#each_rate {|iso_from, iso_to, rate| ... } ⇒ Enumerator
Iterate over rate tuples (iso_from, iso_to, rate)
90 91 92 93 94 95 96 97 98 99 |
# File 'lib/money/rates_store/memory.rb', line 90 def each_rate(&block) enum = Enumerator.new do |yielder| index.each do |key, rate| iso_from, iso_to = key.split(INDEX_KEY_SEPARATOR) yielder.yield iso_from, iso_to, rate end end block_given? ? enum.each(&block) : enum end |
#get_rate(currency_iso_from, currency_iso_to) ⇒ Numeric
Retrieve the rate for the given currencies. Uses Mutex to synchronize data access. Delegates to Money::RatesStore::Memory
56 57 58 |
# File 'lib/money/rates_store/memory.rb', line 56 def get_rate(currency_iso_from, currency_iso_to) transaction { index[rate_key_for(currency_iso_from, currency_iso_to)] } end |
#marshal_dump ⇒ Object
60 61 62 |
# File 'lib/money/rates_store/memory.rb', line 60 def marshal_dump [self.class, , index] end |
#transaction(&block) ⇒ Object
Wraps block execution in a thread-safe transaction
65 66 67 68 69 70 71 72 73 74 75 76 |
# File 'lib/money/rates_store/memory.rb', line 65 def transaction(&block) if @in_transaction || [:without_mutex] block.call self else @mutex.synchronize do @in_transaction = true result = block.call @in_transaction = false result end end end |