class Binnacle::Connection

Attributes

active_url[R]
connection[R]
contact_url[R]

Public Class Methods

new(api_key = nil, api_secret = nil, url = nil) click to toggle source
# File lib/binnacle/connection.rb, line 15
def initialize(api_key = nil, api_secret = nil, url = nil)
  @contact_url = url || Binnacle.configuration.url
  @active_url = @contact_url
  @api_key = api_key || Binnacle.configuration.api_key
  @api_secret = api_secret || Binnacle.configuration.api_secret

  raise Binnacle::ConfigurationError.new("Binnacle URL not provided, set BINNACLE_URL or provide in the constructor") unless @contact_url

  build_connection
  randomize_endpoint
end

Public Instance Methods

build_connection() click to toggle source
# File lib/binnacle/connection.rb, line 55
def build_connection
  @connection ||= Faraday.new(:url => @active_url) do |faraday|
    faraday.request :basic_auth, @api_key, @api_secret
    faraday.request  :url_encoded             # form-encode POST params
    #faraday.response :logger                  # log requests to STDOUT TODO set a client log file
    faraday.adapter :httpclient
  end
end
endpoints() click to toggle source
# File lib/binnacle/connection.rb, line 27
def endpoints
  begin
    response = @connection.get do |req|
      req.url "/api/endpoints"
      req.headers['Content-Type'] = 'application/json'
    end

    if response.status == 401
      Binnacle.binnacle_logger.error("Error communicating with Binnacle (/api/endpoints): #{response.body}")
      []
    else
      JSON.parse(response.body)
    end
  rescue Faraday::Error::ConnectionFailed => cf
    Binnacle.binnacle_logger.error("Error communicating with Binnacle (/api/endpoints): #{cf.message}")
    []
  end
end
randomize_endpoint() click to toggle source
# File lib/binnacle/connection.rb, line 46
def randomize_endpoint
  fresh_endpoints = endpoints
  if fresh_endpoints.size > 1
    Binnacle.configuration.endpoint = fresh_endpoints
    @active_url = Binnacle.configuration.url
    build_connection()
  end
end