class RouteNGNClient::Connection

Constants

USER_AGENT

Attributes

faraday[RW]
options[RW]

Public Class Methods

new(options = {}) click to toggle source
# File lib/routengn_client/connection.rb, line 8
def initialize(options = {})
  @options = options
  @faraday = self.create_faraday(@options[:uri], @options[:api_key]) if @options[:uri]
end

Public Instance Methods

config_request(request, method, path, params, options) click to toggle source
# File lib/routengn_client/connection.rb, line 48
def config_request(request, method, path, params, options)
  case method.to_sym
  when :delete, :get
    request.url(path, params)
  when :post, :put
    request.path = path
    request.body = params unless params.empty?
  end

  request
end
create_faraday(uri, api_key = nil) click to toggle source
# File lib/routengn_client/connection.rb, line 13
def create_faraday(uri, api_key = nil)
  @faraday = Faraday.new uri do |c|
    c.headers['User-Agent'] = USER_AGENT
  
    c.request :oauth2, api_key, :param_name => 'api_key' if api_key
    c.request :multipart
    c.request :url_encoded
    c.request :multi_json

    c.response :xml,  :content_type => /\bxml$/
    c.response :multi_json, symbolize_keys: true, :content_type => /\bjson$/
    c.response :routengn_response
    c.response :logger, RouteNGNClient.logger

    c.use :instrumentation
    c.adapter Faraday.default_adapter
  end
end
delete(path, params={}, options={}, &callback) click to toggle source
# File lib/routengn_client/connection.rb, line 64
def delete(path, params={}, options={}, &callback)
  request(:delete, path, params, options, &callback)
end
get(path, params={}, options={}, &callback) click to toggle source
# File lib/routengn_client/connection.rb, line 60
def get(path, params={}, options={}, &callback)
  request(:get, path, params, options, &callback)
end
post(path, params={}, options={}, &callback) click to toggle source
# File lib/routengn_client/connection.rb, line 68
def post(path, params={}, options={}, &callback)
  request(:post, path, params, options, &callback)
end
put(path, params={}, options={}, &callback) click to toggle source
# File lib/routengn_client/connection.rb, line 72
def put(path, params={}, options={}, &callback)
  request(:put, path, params, options, &callback)
end
request(method, path, params, options, &callback) click to toggle source
# File lib/routengn_client/connection.rb, line 32
def request(method, path, params, options, &callback)
  sent_at = nil
  
  response = @faraday.send(method) { |request|        
    sent_at = Time.now
    request = config_request(request, method, path, params, options)        
  }.on_complete { |env|
    env[:total_time] = Time.now.utc.to_f - sent_at.utc.to_f if sent_at
    env[:request_params] = params
    env[:request_options] = options        
    callback.call(env) if callback
  }

  response
end