class RwandaNationalBank::HistoricRates

Attributes

as_of[R]

Public Class Methods

new(options = {}) click to toggle source
# File lib/rwanda_national_bank/historic_rates.rb, line 12
def initialize options = {}
  @as_of = options[:as_of] || Date.yesterday
end
scrape(as_of) click to toggle source

Scrapes the RNB website for the historic exchange rates of a given day

# File lib/rwanda_national_bank/historic_rates.rb, line 56
def self.scrape as_of
  # POST /index.php?id=384
  uri = URI('http://www.bnr.rw/index.php?id=384')

  # fday=30&fmonth=NOV&fyear=2015&history=Get+History
  params = {
    'fday'    => as_of.strftime('%d'),
    'fmonth'  => as_of.strftime('%b').upcase,
    'fyear'   => as_of.strftime('%Y'),
    'history' => 'Get History'
  }

  response = Net::HTTP.post_form(uri, params)
  dom = Nokogiri::HTML(response.body)
  rows = dom.css('#middlebar > table > tr') # will always return an []

  # RNB does not really use ISO codes thoroughly so we have to map some of their symbols
  translate_currency_symbols = {
    'KD' => 'KWD', # Kuwait Dinar
    'RS' => 'INR', # Indian Rupees
    'LD' => 'LRD' # Lybian Dinar
  }

  Hash[rows.map do |row|
    currency = row.css(':nth-child(1) > a').text
    next if currency.empty?
    avrg = row.css(':nth-child(4)').text
    next if avrg.empty?

    # translate currency to ISO symbol
    currency = translate_currency_symbols[currency.upcase] || currency

    [currency, Float(avrg)] rescue nil
  end.compact]
end

Public Instance Methods

currencies() click to toggle source

Returns a list of ISO currencies

# File lib/rwanda_national_bank/historic_rates.rb, line 29
def currencies
  fail MissingRates unless has_rates?
  @rates.keys
end
has_rates?() click to toggle source

Returns true when reading the website was successful

# File lib/rwanda_national_bank/historic_rates.rb, line 41
def has_rates?
  !@rates.nil? && !@rates.empty?
end
import!() click to toggle source

Triggers the srcaping

# File lib/rwanda_national_bank/historic_rates.rb, line 46
def import!
  @rates = scrape(@as_of)
  has_rates?
end
rate(iso_from, iso_to) click to toggle source
# File lib/rwanda_national_bank/historic_rates.rb, line 16
def rate(iso_from, iso_to)
  fail MissingRates unless has_rates?

  if iso_from == 'RWF'
    rates[iso_to] ? 1/rates[iso_to] : nil
  elsif iso_to == 'RWF'
    rates[iso_from]
  else
    nil
  end
end
rates() click to toggle source

Returns all rates returned

# File lib/rwanda_national_bank/historic_rates.rb, line 35
def rates
  fail MissingRates unless has_rates?
  @rates
end
scrape(as_of) click to toggle source
# File lib/rwanda_national_bank/historic_rates.rb, line 51
def scrape as_of
  self.class.scrape(@as_of)
end