module Apilayer::ConnectionHelper

Public Instance Methods

configs() click to toggle source
# File lib/apilayer/connection_helper.rb, line 9
def configs
  @configs ||= init_configs
end
configure() { |configs| ... } click to toggle source
# File lib/apilayer/connection_helper.rb, line 17
def configure(&block)
  self.reset_connection
  yield(configs)
end
connection() click to toggle source

Creates a connection for the extended module to an apilayer-service, such as currencylayer and vatlayer. Uses access_key(s) configured with Apilayer module.

# File lib/apilayer/connection_helper.rb, line 25
def connection
  @connection ||= ::Faraday.new(
    :url => "#{protocol}://apilayer.net",
    :params => {"access_key" => self.configs[:access_key]}
  )
end
get_and_parse(url, params={}) click to toggle source

Makes a get-request to apilayer's service and parses the JSON response into a Hash

# File lib/apilayer/connection_helper.rb, line 43
def get_and_parse(url, params={})
  resp = get_request(url, params)
  parse_response(resp)
end
get_request(slug, params={}) click to toggle source

Makes a get-request to apilayer's service

# File lib/apilayer/connection_helper.rb, line 50
def get_request(slug, params={})
  # calls connection method on the extended module
  connection.get do |req|
    req.url "api/#{slug}"
    params.each_pair do |k,v|
      req.params[k] = v
    end
  end
end
init_configs() click to toggle source
# File lib/apilayer/connection_helper.rb, line 4
def init_configs
  keys = Struct.new(:access_key, :https)
  keys.new
end
parse_response(resp) click to toggle source

Parses the JSON response from apilayer into a Hash When errors are returned by apilayer, the 'info' and 'code' from its error will be used to raise an Apilayer::Error

# File lib/apilayer/connection_helper.rb, line 63
def parse_response(resp)
  body = JSON.parse(resp.body)
  if body['error']
    raise Apilayer::Error.new(
      body['error']['info'],
      body['error']['code']
    )
  else
    body
  end
end
protocol() click to toggle source
# File lib/apilayer/connection_helper.rb, line 32
def protocol
  self.configs[:https] ? "https" : "http"
end
reset_configs!() click to toggle source
# File lib/apilayer/connection_helper.rb, line 13
def reset_configs!
  @configs = init_configs
end
reset_connection() click to toggle source

Resets the connection for the extended module. Used when the user needs to re-enter his/her access_key(s)

# File lib/apilayer/connection_helper.rb, line 37
def reset_connection
  @connection = nil
end