Module: Exchange::ExternalAPI

Defined in:
lib/exchange/external_api/base.rb,
lib/exchange/external_api/ecb.rb,
lib/exchange/external_api/xml.rb,
lib/exchange/external_api/call.rb,
lib/exchange/external_api/json.rb,
lib/exchange/external_api/random.rb,
lib/exchange/external_api/xavier_media.rb,
lib/exchange/external_api/configuration.rb,
lib/exchange/external_api/open_exchange_rates.rb

Overview

The external API module. Every class Handling an API has to be placed here and inherit from base. It has to call an api and define a rates hash, an exchange base and a unix timestamp. The call will get cached automatically with the right structure Allows for easy extension with an own api, as shown below

Examples:

Easily connect to your custom API by writing an ExternalAPI Class

module Exchange
  module ExternalAPI

    # Inherit from Json to write for a json api, and the json gem is automatically loaded
    # Inherit from XML to write for an xml api, and nokogiri is automatically loaded
    # 
    class MyCustom < Json

      # Define here which currencies your API can handle
      #
      CURRENCIES = %W(usd chf).map(&:to_sym)

      # Every instance of ExternalAPI Class has to have an update function which 
      # gets the rates from the API
      #
      def update(opts={})

        # assure that you will get a Time object for the historical dates
        #
        time = helper.assure_time(opts[:at]) 

        # Call your API (shown here with a helper function that builds your API URL). 
        # Like this, your calls will get cached.
        #
        Call.new(api_url(time), :at => time) do |result|

        # Assign the currency conversion base.
        # Attention, this is readonly, self.base= won't work
        #
        @base                 = result['base']

        # assign the rates, this has to be a hash with the following format: 
        # {'USD' => 1.23242, 'CHF' => 1.34323}. 
        #
        # Attention, this is readonly, self.rates= won't work
        #
        @rates                = result['rates']

        # Timestamp the api call result. This may come in handy to assure you have 
        # the right result. 
        #
        # Attention, this is readonly, self.timestamp= won't work
        #
        @timestamp            = result['timestamp'].to_i

      end

      private

        def api_url(time)
          # code a helper function that builds your api url for the specified time
        end

    end
  end
end

# Now, you can configure your API in the configuration. The Symbol will get camelcased and constantized
#
Exchange::Configuration.api.subclass = :my_custom

# Have fun, and don't forget to write tests.

Author:

  • Beat Richartz

Since:

  • 0.1

Version:

  • 0.1

Defined Under Namespace

Classes: Base, Call, Configuration, Ecb, Json, OpenExchangeRates, Random, XML, XavierMedia

Constant Summary collapse

APIError =

The Api Error to throw when an API Call fails

Since:

  • 0.1

Class.new Error