require "net/http"
require "open-uri"
require "hpricot"

# makes 1284.eur.to.usd types of queries possible
class CurrencyConverter

Currencies = { :huf => "HUF", :eur => "EUR", :usd => "USD", :gbp => "GBP", :chf => "CHF" }

# these methods "close" the quote.
# when they are called, it means all data is ready
# the quote can be sent.
class_eval do
Currencies.each_key do |curr|
define_method curr do
@to = curr
calculate
end
end
end

def initialize(amount, from=nil, to=nil)
@amount = amount
#FIXME: !Currencies.include?(from) => "No such currency"
@from = from
@to = to
end

def send_request_for_quote
from_as_param = @from.to_s.upcase
to_as_param = @to.to_s.upcase
url = "http://xurrency.com/#{[@amount, @from, @to].join('/')}/feed"
doc = Hpricot(open(url).read)
(doc/'dc:value').inner_html
end

def calculate
response = send_request_for_quote
response
# rate = get_conversion_rate(response)
# @amount * rate
# "#{@amount} #{@from} #{@to}"
end

def to
self
end

end

class Fixnum

def method_missing(name)
CurrencyConverter.new(self, name)
end

end