class Nbppl::Client

Constants

NPB_PL_API_URL

Public Class Methods

current() click to toggle source
# File lib/nbppl.rb, line 14
def self.current
  @current ||= Client.new
end
new() click to toggle source
# File lib/nbppl.rb, line 18
def initialize
  @cache = Hash.new { |h,k| h[k] = {} }
end

Public Instance Methods

closest_mid_rate(currency, date = Date.today) click to toggle source
# 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) click to toggle source
# 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

Private Instance Methods

parse_response(response) click to toggle source
# File lib/nbppl.rb, line 45
def parse_response(response)
  case response.code
  when "404" 
    nil
  when "200"
    JSON.parse(response.body)
  else
    message = "#{response.code}, #{response.body}".force_encoding("UTF-8")
    raise ErrorResponse.new(message)
  end
end