Class: Nbppl::Client

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

Constant Summary collapse

NPB_PL_API_URL =
"http://api.nbp.pl/api"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeClient

Returns a new instance of Client.



18
19
20
# File 'lib/nbppl.rb', line 18

def initialize
  @cache = Hash.new { |h,k| h[k] = {} }
end

Class Method Details

.currentObject



14
15
16
# File 'lib/nbppl.rb', line 14

def self.current
  @current ||= Client.new
end

Instance Method Details

#closest_mid_rate(currency, date = Date.today) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/nbppl.rb', line 35

def closest_mid_rate(currency, date = Date.today)
  rate = nil
  until rate = fetch_mid_rate(currency, date)
    date -= 1
  end
  [rate, date]
end

#fetch_mid_rate(currency, date = Date.today) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/nbppl.rb', line 22

def fetch_mid_rate(currency, date = Date.today)
  if @cache[currency].has_key?(date.to_s)
    return @cache[currency][date.to_s]
  end
  
  url = "#{NPB_PL_API_URL}/exchangerates/rates/a/#{currency}/#{date}?format=json"
  uri = URI(url)
  response = Net::HTTP.get_response(uri)
  
  rate = parse_response(response)
  @cache[currency][date.to_s] = rate && rate["rates"].first["mid"]
end