Report abuse

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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