Class: Leadcli::ApiCaller

Inherits:
Object
  • Object
show all
Includes:
Routes
Defined in:
lib/leadcli/api_caller.rb

Constant Summary collapse

DEFAULT_RETRY_LIMIT =
1

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Routes

#create_endpoint, #create_url, #delete_endpoint, #delete_url

Constructor Details

#initialize(endpoint, options = {}) ⇒ ApiCaller

Returns a new instance of ApiCaller.



12
13
14
15
16
# File 'lib/leadcli/api_caller.rb', line 12

def initialize(endpoint, options={})
  @endpoint, @options = endpoint, options
  @connection_attempts = 0
  @max_connection_attempts = options[:max_connection_attempts] || DEFAULT_RETRY_LIMIT
end

Instance Attribute Details

#connection_attemptsObject (readonly)

Returns the value of attribute connection_attempts.



8
9
10
# File 'lib/leadcli/api_caller.rb', line 8

def connection_attempts
  @connection_attempts
end

#endpointObject (readonly)

Returns the value of attribute endpoint.



8
9
10
# File 'lib/leadcli/api_caller.rb', line 8

def endpoint
  @endpoint
end

#max_connection_attemptsObject

Returns the value of attribute max_connection_attempts.



7
8
9
# File 'lib/leadcli/api_caller.rb', line 7

def max_connection_attempts
  @max_connection_attempts
end

#optionsObject (readonly)

Returns the value of attribute options.



8
9
10
# File 'lib/leadcli/api_caller.rb', line 8

def options
  @options
end

Instance Method Details

#call(obj) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/leadcli/api_caller.rb', line 18

def call(obj)
  method, url = send("#{endpoint}_endpoint", options[:url_options] || {})
  Leadcli.debug("API CALL: #{method} #{url}")

  while connection_attempts < max_connection_attempts
    sleep_if_retrying

    response = make_call(method, url)
    valid_response_codes = (200..207).to_a
    if valid_response_codes.include?(response.code.to_i)
      if options[:success]
        Leadcli.debug("CALLING SUCCESS HANDLER: #{options[:success]}")
        obj.send(options[:success], response)
      end
      success = true
      break
    end
  end

  if !success && options[:failure]
    obj.send(options[:failure], response)
  end
rescue Errno::ECONNREFUSED => error
  Leadcli.debug("Remote server down : #{error}")
end