Skip to content

Instantly share code, notes, and snippets.

@lukeredpath
Created November 30, 2009 19:38
Show Gist options
  • Save lukeredpath/245670 to your computer and use it in GitHub Desktop.
Save lukeredpath/245670 to your computer and use it in GitHub Desktop.
require 'money'
require 'xe_exchange'
Money.default_bank = XE::Exchange.instance
ten_dollars = Money.new(1000, 'USD')
ten_dollars_in_pounds = ten_dollars.exchange_to('GBP')
require 'open-uri'
require 'hpricot'
require 'singleton'
module XE
class Exchange
include Singleton
def initialize
@scraper = Scraper.new
@rates = {}
end
def exchange(cents, from_currency, to_currency)
(cents * get_rate(from_currency, to_currency)).floor
end
def get_rate(from_currency, to_currency)
@rates[[from_currency, to_currency]] ||=
@scraper.get_rate(from_currency, to_currency)
end
end
class Scraper
URL = "http://www.xe.com/ucc/convert.cgi?Amount=0f&From=%s&To=%s"
def get_rate(from, to)
document = open(URL % [from, to]) { |f| Hpricot(f) }
elements = (document / 'span.XEsmall')
(elements)[1].inner_text.match(/(\d+\.\d+)/)[0].to_f
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment