class MoneyExchange::Exchange

Public Class Methods

calc(money, target) click to toggle source
# File lib/money_exchange.rb, line 44
def calc(money, target)
  res = money.amount * rate(money.currency, target)
  (res * 100).round.to_f / 100
end

Private Class Methods

call_google_currency_api(base, target) click to toggle source
# File lib/money_exchange.rb, line 70
def call_google_currency_api(base, target)
  uri = "http://www.google.com/ig/calculator"
  query = "?hl=en&q=1#{base}=?#{target}"
  URI.parse(uri+query).read
rescue OpenURI::HTTPError => e
  abort "HTTP Access Error:#{e}"
end
fix_json(json) click to toggle source

Because Google Currency API returns a broken json.

# File lib/money_exchange.rb, line 66
def fix_json(json)
  json.gsub(/(\w+):/, '"\1":')
end
parse_rate(response) click to toggle source
# File lib/money_exchange.rb, line 55
def parse_rate(response)
  body = JSON.parse(fix_json response)

  if ['0', ''].include?(body['error']) # when no error
    body['rhs'].split(',')[0].to_f
  else
    raise NoCurrencyDataError
  end
end
rate(base, target) click to toggle source
# File lib/money_exchange.rb, line 50
def rate(base, target)
  response = call_google_currency_api(base, target)
  rate = parse_rate(response)
end