class CoinSync::CurrencyConverters::NBP

Constants

BASE_URL
POLISH_TIMEZONE

Public Instance Methods

get_conversion_rate(from:, to:, time:) click to toggle source
# File lib/coinsync/currency_converters/nbp.rb, line 20
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"

  raise "Only conversions to PLN are supported" if to.code != 'PLN'

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

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

  response = Request.get("#{BASE_URL}/exchangerates/rates/a/#{from.code}/#{date - 8}/#{date - 1}/?format=json")

  case response
  when Net::HTTPSuccess
    json = JSON.parse(response.body)
    rate = json['rates'] && json['rates'].last && json['rates'].last['mid']
    raise NoDataException.new("No exchange rate found for #{from.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