class NbuRates

Constants

VERSION

Attributes

refreshed_at[R]

Public Class Methods

new(date = Date.today) click to toggle source
# File lib/nbu_rates.rb, line 15
def initialize(date = Date.today)
  @refreshed_at = Time.now
  
  parse!(date)
end

Public Instance Methods

exchange(money, currency_to) click to toggle source
# File lib/nbu_rates.rb, line 25
def exchange(money, currency_to)
  currency_from = money.currency.iso_code
  
  money.with_currency(currency_to) * rate(currency_from) / rate(currency_to)
end
rate(currency_code) click to toggle source
# File lib/nbu_rates.rb, line 21
def rate(currency_code)
  @rates[currency_code.upcase]
end

Private Instance Methods

parse!(date) click to toggle source
# File lib/nbu_rates.rb, line 33
def parse!(date)
  date = date.strftime('%d.%m.%Y')
  url = "https://bank.gov.ua/NBU_Exchange/exchange?date=#{date}"
  
  response = URI.open(url).read
  xml_doc = Nokogiri::XML(response)

  result = 
    xml_doc.css('ROW').map do |node| 
      # amount -- price in UAH per X units
      # units -- quantity of valute
      amount = BigDecimal(node.css('Amount').text, 10)
      units = node.css('Units').text.to_i
      [
        node.css('CurrencyCodeL').text, 
        amount / units
      ]
    end

  result.push(['UAH', 1])

  @rates = result.to_h
end