class BankOfTanzania::HistoricRates

Attributes

as_of[R]

Public Class Methods

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

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

# File lib/bank_of_tanzania/historic_rates.rb, line 90
def self.scrape as_of
  uri = URI('http://www.bot-tz.org/FinancialMarkets/ExchangeRates/ShowExchangeRates.asp')
  params = { 'SelectedExchandeDate' => as_of.strftime('%m/%d/%y') } # sic!
  response = Net::HTTP.post_form(uri, params)

  dom = Nokogiri::HTML(response.body)
  rows = dom.css('#table1 > tr > td > table > tr > td > div > table > tr > td > table > tr')

  Hash[rows.map do |row|
    currency = TRANSLATE[row.css(':nth-child(1) font').text.split.join(' ')]
    buy = Float(row.css(':nth-child(3) font').text.gsub(',', '')) rescue nil
    sell = Float(row.css(':nth-child(4) font').text.gsub(',', '')) rescue nil
    next if currency.nil? || buy.nil? || sell.nil?

    # average of by and sell, divide by 100 b/c conversion is given in 100 units
    [currency, (buy + sell)/200]
  end.compact]
end

Public Instance Methods

currencies() click to toggle source

Returns a list of ISO currencies

# File lib/bank_of_tanzania/historic_rates.rb, line 63
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/bank_of_tanzania/historic_rates.rb, line 75
def has_rates?
  !@rates.nil? && !@rates.empty?
end
import!() click to toggle source

Triggers the scraping

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

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

Returns all rates returned

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