Class: CoinSync::CurrencyConverters::NBP

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

Defined Under Namespace

Classes: BadRequestException, Exception, NoDataException

Constant Summary collapse

BASE_URL =
"https://api.nbp.pl/api"
POLISH_TIMEZONE =
TZInfo::Timezone.get('Europe/Warsaw')

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



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
47
48
49
# 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