Sha256: 2fce9ff1b09d992de95a26d1146b426d76de8c23529d38864a9ce26663a3a4eb

Contents?: true

Size: 1.16 KB

Versions: 1

Compression:

Stored size: 1.16 KB

Contents

require 'danconia/pair'

module Danconia
  module Exchanges
    class Exchange
      attr_reader :store

      def initialize store: Stores::InMemory.new
        @store = store
      end

      def rate from, to
        return 1.0 if from == to

        pair = Pair.new(from, to)
        rates = direct_and_inverted_rates()
        rates[pair] or indirect_rate(pair, rates) or raise Errors::ExchangeRateNotFound.new(from, to)
      end

      def rates
        @store.rates
      end

      def update_rates!
        @store.save_rates fetch_rates
      end

      private

      # Returns the original rates plus the inverted ones, to simplify rate finding logic.
      def direct_and_inverted_rates
        rates.each_with_object({}) do |(pair_str, rate), rs|
          pair = Pair.parse(pair_str)
          rs[pair] = rate
          rs[pair.invert] ||= 1.0 / rate
        end
      end

      def indirect_rate ind_pair, rates
        if (from_pair = rates.keys.detect { |(pair, rate)| pair.from == ind_pair.from }) &&
           (to_pair = rates.keys.detect { |(pair, rate)| pair.to == ind_pair.to })
          rates[from_pair] * rates[to_pair]
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
danconia-0.2.9 lib/danconia/exchanges/exchange.rb