Class: Binnacle::Connection

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/binnacle/connection.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_key = nil, api_secret = nil, url = nil) ⇒ Connection

Returns a new instance of Connection.



15
16
17
18
19
20
21
22
23
24
25
# 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

Instance Attribute Details

#active_urlObject (readonly)

Returns the value of attribute active_url.



10
11
12
# File 'lib/binnacle/connection.rb', line 10

def active_url
  @active_url
end

#connectionObject (readonly)

Returns the value of attribute connection.



9
10
11
# File 'lib/binnacle/connection.rb', line 9

def connection
  @connection
end

#contact_urlObject (readonly)

Returns the value of attribute contact_url.



11
12
13
# File 'lib/binnacle/connection.rb', line 11

def contact_url
  @contact_url
end

Instance Method Details

#build_connectionObject



55
56
57
58
59
60
61
62
# 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

#endpointsObject



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# 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_endpointObject



46
47
48
49
50
51
52
53
# 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