Class: Convertator::Converter

Inherits:
Object
  • Object
show all
Includes:
Utils
Defined in:
lib/convertator/converter.rb

Defined Under Namespace

Classes: UnknownCurrencyError

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Utils

#normalize_currency, #symbolize_keys

Constructor Details

#initialize(provider = :cbr, accuracy = 10) {|_self| ... } ⇒ Converter

Returns a new instance of Converter.

Yields:

  • (_self)

Yield Parameters:



14
15
16
17
18
19
# File 'lib/convertator/converter.rb', line 14

def initialize(provider = :cbr, accuracy = 10)
  @provider = load_provider(provider)
  @accuracy = accuracy
  @chain = [] << @provider
  yield(self) if block_given?
end

Instance Attribute Details

#providerObject (readonly)

Returns the value of attribute provider.



12
13
14
# File 'lib/convertator/converter.rb', line 12

def provider
  @provider
end

Instance Method Details

#add(middleware) ⇒ Object



21
22
23
24
# File 'lib/convertator/converter.rb', line 21

def add(middleware)
  middleware.prev = @chain.last
  @chain << middleware
end

#convert(amount, currency_from, currency_to) ⇒ Object



41
42
43
# File 'lib/convertator/converter.rb', line 41

def convert(amount, currency_from, currency_to)
  round(amount * ratio(currency_from, currency_to))
end

#convert_multi(amount, currency_from, currencies_to) ⇒ Object



49
50
51
52
53
# File 'lib/convertator/converter.rb', line 49

def convert_multi(amount, currency_from, currencies_to)
  currencies_to.map do |currency_to|
    convert(amount, currency_from, currency_to)
  end
end

#convert_multi_s(amount, currency_from, currencies_to) ⇒ Object



55
56
57
58
59
# File 'lib/convertator/converter.rb', line 55

def convert_multi_s(amount, currency_from, currencies_to)
  currencies_to.map do |currency_to|
    convert_s(amount, currency_from, currency_to)
  end
end

#convert_s(amount, currency_from, currency_to) ⇒ Object



45
46
47
# File 'lib/convertator/converter.rb', line 45

def convert_s(amount, currency_from, currency_to)
  convert(amount, currency_from, currency_to).to_digits
end

#rate(currency) ⇒ Object



30
31
32
33
34
35
# File 'lib/convertator/converter.rb', line 30

def rate(currency)
  currency = normalize_currency(currency)
  rate = rates[currency]
  raise UnknownCurrencyError, "Unknown currency #{currency}" unless rate
  round(BigDecimal.new(rate, @accuracy))
end

#ratesObject



26
27
28
# File 'lib/convertator/converter.rb', line 26

def rates
  symbolize_keys(@chain.last.call)
end

#ratio(currency_from, currency_to) ⇒ Object



37
38
39
# File 'lib/convertator/converter.rb', line 37

def ratio(currency_from, currency_to)
  round(rate(currency_from) / rate(currency_to))
end