Class: Exchange::ExternalAPI::Call

Inherits:
Base
  • Object
show all
Defined in:
lib/exchange/external_api/call.rb

Overview

A class to handle API calls in a standardized way for all APIs

Author:

  • Beat Richartz

Since:

  • 0.1

Version:

  • 0.1

Instance Attribute Summary

Attributes inherited from Base

#base, #cache, #helper, #rates, #timestamp

Instance Method Summary collapse

Methods inherited from Base

#convert, #rate, #test_for_rates_and_raise_if_nil, #to_hash!

Constructor Details

#initialize(url, options = {}) {|Nokogiri::XML, Hash| ... } ⇒ Nokogiri::XML, Hash

Initialization of the Call class is the call itself. This means that every instance of the class will only exist during the call

Examples:

Call an API an yield the result

Exchange::ExternalAPI::Call.new('http://yourapiurl.com', :format => :xml) do |result|
  # Do something with the result here, for example
  rates = {}
  result.css('rates').each do |rate|
    rates.merge! rate.css('currency').children.to_s => rate.css('rate').children.to_s.to_f
  end
end

Call the API and do something with the result

result = Exchange::ExternalAPI::Call.new('http://yourapiurl.com', :format => :xml)
# Do something with that result

Parameters:

  • url (String)

    The url of the API to call

  • options (Hash) (defaults to: {})

    The options of the API call

Options Hash (options):

  • :at (Time)

    The time of the historical exchange rate file to get

  • :api (Class)

    The class to generate the key for

  • :retries (Integer)

    The number of retries if the API Call should fail with a HTTP Error

  • :retry_with (Array)

    an Array of urls to retry the call with (if the API does not have a file for the specified date). These values will be shifted until a call succeeds or the number of maximum retries is reached.

  • :format (Symbol)

    The format to return / yield the API call result in, defaults to :json

Yields:

  • (Nokogiri::XML, Hash)

    The result of the API call, either nokogiri parsed XML or a hash loaded from JSON

Since:

  • 0.1


34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/exchange/external_api/call.rb', line 34

def initialize url, options={}, &block
  Exchange::GemLoader.new(options[:format] == :xml ? 'nokogiri' : 'json').try_load
          
  result = cache_config.subclass.cached(options[:api] || config.subclass, options) do
    load_url(url, options[:retries] || config.retries, options[:retry_with])
  end
  
  parsed = options[:format] == :xml ? Nokogiri::XML.parse(result.sub("\n", '')) : ::JSON.load(result)
  
  return parsed unless block_given?
  yield  parsed
end