Module: Lbank
- Defined in:
- lib/lbank.rb,
lib/lbank/errors.rb,
lib/lbank/version.rb
Defined Under Namespace
Classes: Error, MemoryCache, ResponseError
Constant Summary
collapse
- RATE_TYPE =
'LT'
- TIMEZONE =
'Europe/Vilnius'
- URL =
'http://www.lb.lt/webservices/FxRates/FxRates.asmx/getFxRates'
- LTL =
'LTL'
- LTL_RATE =
BigDecimal('3.45280')
- VERSION =
'2.0.0'
Class Method Summary
collapse
Class Method Details
.bank_date(time) ⇒ Object
61
62
63
64
65
66
67
68
|
# File 'lib/lbank.rb', line 61
def bank_date(time)
if time.is_a?(Date) && !time.is_a?(DateTime)
time.strftime('%Y-%m-%d')
else
local_time = TZInfo::Timezone.get(TIMEZONE).utc_to_local(time.to_time.utc)
local_time.strftime('%Y-%m-%d')
end
end
|
.cache ⇒ Object
20
21
22
|
# File 'lib/lbank.rb', line 20
def cache
@cache ||= MemoryCache.new
end
|
.cache=(store) ⇒ Object
24
25
26
|
# File 'lib/lbank.rb', line 24
def cache=(store)
@cache = store
end
|
.cache_key(date) ⇒ Object
57
58
59
|
# File 'lib/lbank.rb', line 57
def cache_key(date)
"lbank-#{date}"
end
|
.connection ⇒ Object
70
71
72
73
74
75
76
77
|
# File 'lib/lbank.rb', line 70
def connection
@connection ||= Faraday.new do |builder|
builder.request :url_encoded
builder.response :raise_error
builder.response :xml, content_type: /\bxml$/
builder.adapter Faraday.default_adapter
end
end
|
.convert_currency(amount, from_currency, to_currency, time = nil) ⇒ Object
49
50
51
52
53
54
55
|
# File 'lib/lbank.rb', line 49
def convert_currency(amount, from_currency, to_currency, time = nil)
rates = currency_rates(time)
from_rate = rates[from_currency.to_s]
to_rate = rates[to_currency.to_s]
amount / from_rate * to_rate
end
|
.currency_rates(time = nil) ⇒ Object
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
# File 'lib/lbank.rb', line 28
def currency_rates(time = nil)
date = bank_date(time || Time.now)
cache.fetch(cache_key(date)) do
response = connection.post(URL, tp: RATE_TYPE, dt: date)
error = response.body['FxRates']['OprlErr']
raise ResponseError.new(error['Desc']) if error
fx_rates = response.body['FxRates']['FxRate']
rates = { fx_rates[0]['CcyAmt'][0]['Ccy'] => 1 }
rates[LTL] ||= LTL_RATE
fx_rates.each_with_object(rates) do |rate, result|
base, foreign = rate['CcyAmt']
result[foreign['Ccy']] = BigDecimal(foreign['Amt']) / BigDecimal(base['Amt'])
end
end
end
|