class CurrencyConverter::Yahoo

Constants

API_URL

Attributes

from_currency[R]

Returns the Symbol of 'base' currency

rates[R]

Returns the array of currencies rates

to_currency[R]

Returns the Symbol of 'quot' currency

Public Class Methods

new() click to toggle source
# File lib/currency_converter/yahoo.rb, line 19
def initialize
  response = fetch_data

  parse_rates(response)
end

Public Instance Methods

exchange(base, quot, amount) click to toggle source

Receive the amount of you desire currency.

@param [String, String, Numeric] other currency to exchange to.

@return [amount]

@example currency_converter = CurrencyConverter::Yahoo.new currency_converter.exchange('USD', 'EUR', 100) currency_converter.exchange('USD', 'INR', 100)

# File lib/currency_converter/yahoo.rb, line 35
def exchange(base, quot, amount)
  @from_currency = base.upcase.to_sym
  @to_currency = quot.upcase.to_sym

  validate_currency

  base_rate = rates[from_currency].to_f
  quot_rate = rates[to_currency].to_f

  rate = base_rate.zero? ? 0 : (quot_rate / base_rate)
  validate_rate(rate)

  amount * rate
end

Private Instance Methods

fetch_data() click to toggle source
# File lib/currency_converter/yahoo.rb, line 52
def fetch_data
  Net::HTTP.get(URI(API_URL))
end
parse_rates(html) click to toggle source
# File lib/currency_converter/yahoo.rb, line 56
def parse_rates(html)
  @rates = { USD: 1.0 }

  result = Nokogiri::HTML(html)

  result.css('resource').each do |resource|
    symbol = resource.xpath(".//field[@name='symbol']").text[0,3]
    price  = resource.xpath(".//field[@name='price']").text

    rates[symbol.upcase.to_sym] = price.to_f unless symbol.nil? && price.nil?
  end
end
validate_currency() click to toggle source
# File lib/currency_converter/yahoo.rb, line 69
def validate_currency
  raise UnknownCurrency.new(from_currency) unless CURRENCIES.has_key?(from_currency)
  raise UnknownCurrency.new(to_currency) unless CURRENCIES.has_key?(to_currency)
end
validate_rate(rate) click to toggle source
# File lib/currency_converter/yahoo.rb, line 74
def validate_rate(rate)
  raise MissingExchangeRate.new(from_currency, to_currency) if rate.zero?
end