Class: CoinSync::CurrencyConverters::ExchangeRatesAPI

Inherits:
Base
  • Object
show all
Defined in:
lib/coinsync/currency_converters/exchangeratesapi.rb

Defined Under Namespace

Classes: BadRequestException, Exception, NoDataException

Constant Summary collapse

BASE_URL =
"https://exchangeratesapi.io/api"
ECB_TIMEZONE =
TZInfo::Timezone.get('Europe/Berlin')

Instance Method Summary collapse

Methods inherited from Base

#convert, #finalize, #initialize, register_converter

Constructor Details

This class inherits a constructor from CoinSync::CurrencyConverters::Base

Instance Method Details

#get_conversion_rate(from:, to:, time:) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/coinsync/currency_converters/exchangeratesapi.rb', line 19

def get_conversion_rate(from:, to:, time:)
  (from.is_a?(FiatCurrency)) or raise "#{self.class}: 'from' should be a FiatCurrency"
  (to.is_a?(FiatCurrency)) or raise "#{self.class}: 'to' should be a FiatCurrency"
  (time.is_a?(Time)) or raise "#{self.class}: 'time' should be a Time"

  date = ECB_TIMEZONE.utc_to_local(time.utc).to_date

  if rate = @cache[from, to, date]
    return rate
  end

  response = Request.get("#{BASE_URL}/#{date}?base=#{from.code}")

  case response
  when Net::HTTPSuccess
    json = JSON.parse(response.body)
    rate = json['rates'][to.code.upcase]
    raise NoDataException.new("No exchange rate found for #{to.code.upcase}") if rate.nil?

    @cache[from, to, date] = rate

    return rate
  when Net::HTTPBadRequest
    raise BadRequestException.new(response)
  else
    raise Exception.new(response)
  end
end