Class: CcyConvertor::RateProvider

Inherits:
Object
  • Object
show all
Extended by:
ProcessAndValidateOption, RateCache
Defined in:
lib/ccy_convertor/rate_providers/rate_provider.rb

Direct Known Subclasses

CurrencyLayer, OpenExchangeRate, YahooFinance

Class Attribute Summary collapse

Attributes included from RateCache

#cache_duration

Class Method Summary collapse

Methods included from RateCache

cache, cache_duration_nil?, cache_key

Methods included from ProcessAndValidateOption

validate_amount!, validate_currency_codes!, validate_currency_support!, validate_options!, validate_presence_of_hash_keys!

Class Attribute Details

.api_keyObject



12
13
14
15
16
17
# File 'lib/ccy_convertor/rate_providers/rate_provider.rb', line 12

def api_key
  if api_key_nil?
    raise CcyConvertor::NoApiKeyPresent, "api_key not set for #{name}"
  end
  @api_key ||= CcyConvertor.configuration.api_keys[rate_provider_name]
end

Class Method Details

.api_key_nil?Boolean

Returns:

  • (Boolean)


19
20
21
22
23
# File 'lib/ccy_convertor/rate_providers/rate_provider.rb', line 19

def api_key_nil?
  @api_key.nil? &&
  (CcyConvertor.configuration.api_keys.nil? ||
  CcyConvertor.configuration.api_keys[rate_provider_name].nil?)
end

.convert(options) ⇒ Object



53
54
55
56
57
58
# File 'lib/ccy_convertor/rate_providers/rate_provider.rb', line 53

def convert(options)
  validate_options!(options)
  converted_rate = options[:amount] * rate(options[:to_ccy], options[:from_ccy])
  return converted_rate if CcyConvertor.configuration.round_up_amount.nil?
  converted_rate.round(CcyConvertor.configuration.round_up_amount)
end

.rate_from_rate_matrix(from_ccy, to_ccy) ⇒ Object Also known as: rate



46
47
48
49
50
# File 'lib/ccy_convertor/rate_providers/rate_provider.rb', line 46

def rate_from_rate_matrix(from_ccy, to_ccy)
  rate_matrix = rate_matrix()
  validate_currency_support!([from_ccy, to_ccy], rate_matrix)
  rate_matrix[from_ccy].to_f / rate_matrix[to_ccy].to_f
end

.rate_matrix_response(base_ccy = nil) ⇒ Object



38
39
40
# File 'lib/ccy_convertor/rate_providers/rate_provider.rb', line 38

def rate_matrix_response(base_ccy=nil)
  response_hash(rest_url_for_rate_matrix(base_ccy))
end

.rate_provider_nameObject



25
26
27
# File 'lib/ccy_convertor/rate_providers/rate_provider.rb', line 25

def rate_provider_name
  self.name.demodulize.underscore.to_sym
end

.rate_response(from_ccy, to_ccy) ⇒ Object



42
43
44
# File 'lib/ccy_convertor/rate_providers/rate_provider.rb', line 42

def rate_response(from_ccy, to_ccy)
  response_hash(rest_url_for_rate(from_ccy, to_ccy))
end

.response_hash(request_url) ⇒ Object



29
30
31
32
33
34
35
36
# File 'lib/ccy_convertor/rate_providers/rate_provider.rb', line 29

def response_hash(request_url)
  cache_key = cache_key(request_url)
  return cache.read(cache_key) if cache.exist?(cache_key)

  response = JSON.parse(Net::HTTP.get(URI(request_url)))
  cache.write(cache_key, response, expires_in: cache_duration)
  response
end