Class: Ubea::CurrencyConverter

Inherits:
Object
  • Object
show all
Defined in:
lib/ubea/currency_converter.rb

Defined Under Namespace

Classes: FreeCurrencyConverterAPI, RateExchange, YahooExchange

Class Method Summary collapse

Class Method Details

.convert(amount, from, to) ⇒ Object



8
9
10
# File 'lib/ubea/currency_converter.rb', line 8

def self.convert(amount, from, to)
  amount * rate(from, to)
end

.rate(from, to) ⇒ Object



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
# File 'lib/ubea/currency_converter.rb', line 12

def self.rate(from, to)
  pair = [from, to].join

  if @rates[pair].nil? || @rates[pair].updated_at < Time.now - 10 * 60

    rate_1 = YahooExchange.get_rate(from, to)

    rate_2 = begin
      RateExchange.get_rate(from, to)
    rescue OpenURI::HTTPError
      FreeCurrencyConverterAPI.get_rate(from, to)
    end

    spread = (1.0 - rate_1 / rate_2).abs * 100
    if spread > 1
      raise "#{spread.to_f}% spread for #{pair}: #{rate_1} vs #{rate_2}!"
    end

    @rates[pair] = OpenStruct.new(
      rate: rate_1,
      updated_at: Time.now
    ).freeze

  end

  @rates[pair].rate
end