lib/oxr.rb in oxr-0.2.0 vs lib/oxr.rb in oxr-0.4.0
- old
+ new
@@ -1,81 +1,86 @@
-require "oxr/version"
+require 'oxr/version'
+require 'oxr/configuration'
require 'date'
require 'json'
require 'open-uri'
-class OXR
- BASE_PATH = 'https://openexchangerates.org/api/'.freeze
+module OXR
+ class Error < StandardError
+ end
- class OXRError < StandardError
- def initialize(message, response)
- super message
- @response = response
+ class ApiError < Error
+ def message
+ cause.message
end
- attr_reader :response
- end
+ def description
+ response['description']
+ end
- def initialize(app_id)
- @app_id = app_id
+ def response
+ @response ||= JSON.load cause.io
+ end
end
- attr_reader :app_id
+ class << self
+ def new(app_id)
+ warn '[DEPRECATION WARNING] OXR.new is depr4ecated.' \
+ " Use OXR class methods instead (from #{caller.first})."
+ configure do |config|
+ config.app_id = app_id
+ end
+ self
+ end
- def [](code)
- latest['rates'][code]
- end
+ def get_rate(code, on: nil)
+ data = if on
+ historical on: on
+ else
+ latest
+ end
+ data['rates'][code.to_s]
+ end
- def latest
- endpoint = sources[:latest] || build_uri_endpoint('latest.json')
- call endpoint
- end
+ alias_method :[], :get_rate
- def historical(on:)
- endpoint = sources[:historical] || \
- build_uri_endpoint('historical/', "#{on.strftime '%Y-%m-%d'}.json")
- call endpoint
- end
+ def currencies
+ call configuration.currencies
+ end
- def currencies
- endpoint = sources[:currencies] || build_uri_endpoint('currencies.json')
- call endpoint
- end
+ def historical(on:)
+ call configuration.historical on
+ end
- def usage
- endpoint= sources[:usage] || build_uri_endpoint('usage.json')
- call endpoint
- end
+ def latest
+ call configuration.latest
+ end
- private
+ def usage
+ call configuration.usage
+ end
- def build_uri_endpoint(*path, **params)
- URI.join(BASE_PATH, *path).tap do |uri|
- uri.query = "app_id=#{app_id}"
+ def reset_sources
+ configure do |config|
+ config.reset_sources
+ end
end
- end
- def call(endpoint)
- JSON.load open endpoint
- rescue OpenURI::HTTPError => e
- case e.message
- when /\A4[[:digit:]]{2}/
- response = JSON.load e.io
- raise OXRError.new response['description'], response
- else
- raise
+ def configure
+ yield configuration if block_given?
+ configuration
end
- end
- def sources
- self.class.sources
- end
+ def configuration
+ @configuration ||= Configuration.new
+ end
- def self.sources
- @sources ||= {}
- end
+ private
- def self.reset_sources
- sources.clear
+ def call(endpoint)
+ JSON.load open endpoint
+ rescue OpenURI::HTTPError => e
+ raise ApiError.new e
+ end
end
end