Class: Money::Distributed::Storage

Inherits:
Object
  • Object
show all
Defined in:
lib/money/distributed/storage.rb

Overview

Storage for ‘Money::Bank::VariableExchange` that stores rates in Redis

Constant Summary collapse

INDEX_KEY_SEPARATOR =
'_TO_'.freeze
REDIS_KEY =
'money_rates'.freeze

Instance Method Summary collapse

Constructor Details

#initialize(redis, cache_ttl = nil) ⇒ Storage

Returns a new instance of Storage.



11
12
13
14
15
16
17
18
19
# File 'lib/money/distributed/storage.rb', line 11

def initialize(redis, cache_ttl = nil)
  @redis = Money::Distributed::Redis.new(redis)

  @cache = {}
  @cache_ttl = cache_ttl
  @cache_updated_at = nil

  @mutex = Mutex.new
end

Instance Method Details

#add_rate(iso_from, iso_to, rate) ⇒ Object



21
22
23
24
25
26
# File 'lib/money/distributed/storage.rb', line 21

def add_rate(iso_from, iso_to, rate)
  @redis.exec do |r|
    r.hset(REDIS_KEY, key_for(iso_from, iso_to), rate)
  end
  clear_cache
end

#each_rateObject



32
33
34
35
36
37
38
39
40
41
# File 'lib/money/distributed/storage.rb', line 32

def each_rate
  enum = Enumerator.new do |yielder|
    cached_rates.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(iso_from, iso_to) ⇒ Object



28
29
30
# File 'lib/money/distributed/storage.rb', line 28

def get_rate(iso_from, iso_to)
  cached_rates[key_for(iso_from, iso_to)]
end

#marshal_dumpObject



48
49
50
# File 'lib/money/distributed/storage.rb', line 48

def marshal_dump
  [self.class, @cache_ttl]
end

#transactionObject



43
44
45
46
# File 'lib/money/distributed/storage.rb', line 43

def transaction
  # We don't need transactions, we all thread safe here
  yield
end