class CbrRates

Constants

VERSION

Attributes

refreshed_at[R]

Public Class Methods

new(date = Date.today) click to toggle source
# File lib/cbr_rates.rb, line 13
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/cbr_rates.rb, line 23
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/cbr_rates.rb, line 19
def rate(currency_code)
  @rates[currency_code.upcase]
end

Private Instance Methods

parse!(date) click to toggle source
# File lib/cbr_rates.rb, line 31
def parse!(date)
  date_string = date.strftime('%d/%m/%Y')
  url =
    "http://www.cbr.ru/scripts/XML_daily.asp?date_req=#{date_string}"

  response = URI.open(url).read
  xml_doc = Nokogiri::XML(response)

  result =
    xml_doc.css('Valute').map do |node|
      value = BigDecimal(node.css('Value').text.gsub(',', '.'), 10)
      amount = node.css('Nominal').text.to_i

      [
        node.css('CharCode').text,
        value / amount
      ]
    end

  result.push(["RUB", 1])

  @rates = result.to_h
end