class MoneyExchange::Store

Constants

CACHE_KEY

Public Class Methods

new(opts = {}) click to toggle source
Calls superclass method
# File lib/money_exchange/store.rb, line 7
def initialize(opts = {})
  super

  @client      = opts[:client]
  @cache_store = opts[:cache_store] || Cache::NullStore.new
  @ttl         = opts[:ttl] || 24 * 60 * 60
  @loaded_at   = nil
  @iso_base    = nil
end

Public Instance Methods

get_rate(iso_from, iso_to) click to toggle source
Calls superclass method
# File lib/money_exchange/store.rb, line 17
def get_rate(iso_from, iso_to)
  load_rates! if stale?

  super || begin
    rate =
      if iso_from == @iso_base
        nil
      elsif inverse_rate = super(iso_to, iso_from)
        1.0 / inverse_rate
      elsif iso_to == @iso_base
        nil
      else
        get_rate(iso_from, @iso_base) * get_rate(@iso_base, iso_to)
      end

    add_rate(iso_from, iso_to, rate)
  end
end

Private Instance Methods

load_rates!() click to toggle source
# File lib/money_exchange/store.rb, line 38
def load_rates!
  data = @cache_store.read(CACHE_KEY)

  unless data
    data = @client.data

    expires_in = data['timestamp'] + @ttl - Time.now.to_i
    @cache_store.write(CACHE_KEY, data, expires_in: expires_in)
  end

  @iso_base = data['base']

  transaction do
    index.clear
    data['rates'].each do |iso_to, rate|
      add_rate(@iso_base, iso_to, rate)
    end
  end

  @loaded_at = Time.now.to_i
end
stale?() click to toggle source
# File lib/money_exchange/store.rb, line 60
def stale?
  @loaded_at.nil? || (@loaded_at + @ttl < Time.now.to_i)
end