Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 724cfd50a0
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 56 lines (45 sloc) 1.775 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 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 47 48 49 50 51 52 53 54 55
require 'rubygems'
require 'open-uri'
require 'nokogiri'
require 'money'

class InvalidCache < StandardError ; end

class NbrbCurrency < Money::Bank::VariableExchange

  NBRB_RATES_URL = 'http://nbrb.by/Services/XmlExRates.aspx'
  CURRENCIES = %w(AUD BGN UAH DKK USD EUR PLN JPY IRR ISK CAD CNY KWD LVL LTL MDL NOK RUB SGD KGS KZT TRY GBP CZK SEK CHF)

  def update_rates(cache=nil)
    exchange_rates(cache).each do |exchange_rate|
      rate = exchange_rate.xpath("Rate").text
      currency = exchange_rate.xpath("CharCode").text
      scale = exchange_rate.xpath("Scale").text
      next if currency == "XDR"
      add_rate(currency, "BYR", (BigDecimal.new(rate) / BigDecimal.new(scale)).to_f)
    end
    add_rate("BYR", "BYR", 1)
  end

  def save_rates(cache)
    raise InvalidCache if !cache
    File.open(cache, "w") do |file|
      io = open(NBRB_RATES_URL) ;
      io.each_line {|line| file.puts line}
    end
  end

  def exchange(cents, from_currency, to_currency)
    exchange_with(Money.new(cents, from_currency), to_currency)
  end

  def exchange_with(from, to_currency)
    rate = get_rate(from.currency, to_currency)
    unless rate
      from_base_rate = get_rate(from.currency, "BYR")
      to_base_rate = get_rate(to_currency, "BYR")
      rate = (BigDecimal.new(from_base_rate, 8) / BigDecimal.new(to_base_rate, 8)).to_f
      raise "Rate #{from.currency} - #{to_currency} unknown!" unless rate
    end
    Money.new(((Money::Currency.wrap(to_currency).subunit_to_unit.to_f / from.currency.subunit_to_unit.to_f) * from.cents * rate).round, to_currency)
  end

  protected

  def exchange_rates(cache=nil)
    rates_source = !!cache ? cache : NBRB_RATES_URL
    doc = Nokogiri::XML(open(rates_source))
    doc.xpath('DailyExRates//Currency')
  end

end
Something went wrong with that request. Please try again.