lib/money-fixer-io.rb in money-fixer-io-0.0.0 vs lib/money-fixer-io.rb in money-fixer-io-0.0.1

- old
+ new

@@ -1,12 +1,10 @@ require "money" -require "money/rates_store/rate_removal_support" require "open-uri" class Money::Bank::FixerIo < Money::Bank::VariableExchange SERVICE_HOST = "api.fixer.io".freeze - SERVICE_PATH = "/".freeze # @return [Hash] Stores the currently known rates. attr_reader :rates class << self @@ -32,13 +30,12 @@ def refresh_rates_expiration! @rates_expiration = Time.now + ttl_in_seconds end end - def initialize(*) - super - @store.extend Money::RatesStore::RateRemovalSupport + def cache + @@money_bank_fixer_io_cache ||= {} # rubocop:disable Style/ClassVars end ## # Clears all rates stored in @rates # @@ -85,17 +82,28 @@ # @bank.get_rate(:USD, :EUR) #=> 0.776337241 def get_rate(from, to, args = {}) expire_rates if args[:exchanged_at] - fetch_rate(from, to, exchanged_at: args.fetch(:exchanged_at)) - raise "stub" + get_rate_with_exchange_rate(from, to, args) else store.get_rate(from, to) || store.add_rate(from, to, fetch_rate(from, to)) end end + def get_rate_with_exchange_rate(from, to, args = {}) + exchanged_at = args.fetch(:exchanged_at).strftime("%Y-%m-%d") + + if cache[from] && cache[from][to] && cache[from][to][exchanged_at] + cache[from][to][exchanged_at] + else + cache[from] ||= {} + cache[from][to] ||= {} + cache[from][to][exchanged_at] = fetch_rate(from, to, exchanged_at: exchanged_at) + end + end + ## # Flushes all the rates if they are expired. # # @return [Boolean] def expire_rates @@ -116,15 +124,16 @@ # @param [String, Symbol, Currency] from Currency to convert from # @param [String, Symbol, Currency] to Currency to convert to # # @return [BigDecimal] The requested rate. def fetch_rate(from, to, args = {}) - from = Currency.wrap(from) - to = Currency.wrap(to) + from = Money::Currency.wrap(from) + to = Money::Currency.wrap(to) + uri = build_uri(from, to, args) - data = JSON.parse(build_uri(from, to, args).read) - rate = data.fetch("rates").fetch(to) + data = JSON.parse(uri.read) + rate = data.fetch("rates").fetch(to.iso_code) rate = 1 / extract_rate(build_uri(to, from).read) if rate < 0.1 rate end ## @@ -132,16 +141,21 @@ # # @param [Currency] from The currency to convert from. # @param [Currency] to The currency to convert to. # # @return [URI::HTTP] - def build_uri(from, _to, _args = {}) + def build_uri(from, _to, args = {}) + if args[:exchanged_at] + path = "/#{args.fetch(:exchanged_at)}" + else + path = "/latest" + end + query = "base=#{from.iso_code}" - query << "&date=#{args.fetch(:exchange_at).strftime("%Y-%m-%D")}" uri = URI::HTTP.build( host: SERVICE_HOST, - path: SERVICE_PATH, + path: path, query: query ) uri end end