Class: ExchangerLocal

Inherits:
ExchangerBase show all
Defined in:
lib/mrpin/core/currency_exchanger/local/exchanger_local.rb

Overview

used for local cache

Constant Summary collapse

EXPIRE_DURATION =

properties

30.minutes

Instance Method Summary collapse

Constructor Details

#initializeExchangerLocal

Returns a new instance of ExchangerLocal.



16
17
18
19
20
21
22
# File 'lib/mrpin/core/currency_exchanger/local/exchanger_local.rb', line 16

def initialize
  super

  @locker = Mutex.new
  #key - from + to, value - hash {timestamp_updated_at: rate: }
  @rates_map = {}
end

Instance Method Details

#get_rate(from_currency, to_currency) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/mrpin/core/currency_exchanger/local/exchanger_local.rb', line 25

def get_rate(from_currency, to_currency)
  result = nil

  @locker.synchronize do
    key = "#{from_currency}_#{to_currency}"

    data = @rates_map[key]

    unless data.nil?
      updated_at = data[:updated_at]
      rate       = data[:rate]

      if Time.now.to_i - updated_at > EXPIRE_DURATION
        @rates_map.delete(key)
      else
        result = rate
      end #check time
    end #check data
  end #locker

  result
end

#set_rate(from_currency, to_currency, rate) ⇒ Object



49
50
51
52
53
54
55
56
57
58
# File 'lib/mrpin/core/currency_exchanger/local/exchanger_local.rb', line 49

def set_rate(from_currency, to_currency, rate)
  return if rate == 0 || rate.nil?

  @locker.synchronize do
    set_rate_unsafe(from_currency, to_currency, rate)
    set_rate_unsafe(to_currency, from_currency, 1.to_f / rate)
  end

  nil
end