Class: Localeapp::ApiCaller

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

Defined Under Namespace

Classes: NonHTTPResponse

Constant Summary collapse

DEFAULT_RETRY_LIMIT =
1

Constants included from Routes

Routes::VERSION

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Routes

#create_translation_endpoint, #export_endpoint, #export_url, #import_endpoint, #import_url, #missing_translations_endpoint, #missing_translations_url, #project_endpoint, #project_url, #remove_endpoint, #remove_url, #rename_endpoint, #rename_url, #translations_endpoint, #translations_url

Constructor Details

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

Returns a new instance of ApiCaller.



15
16
17
18
19
# File 'lib/localeapp/api_caller.rb', line 15

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.



13
14
15
# File 'lib/localeapp/api_caller.rb', line 13

def connection_attempts
  @connection_attempts
end

#endpointObject (readonly)

Returns the value of attribute endpoint.



13
14
15
# File 'lib/localeapp/api_caller.rb', line 13

def endpoint
  @endpoint
end

#max_connection_attemptsObject

we can retry more in the gem than we can when running in process



11
12
13
# File 'lib/localeapp/api_caller.rb', line 11

def max_connection_attempts
  @max_connection_attempts
end

#optionsObject (readonly)

Returns the value of attribute options.



13
14
15
# File 'lib/localeapp/api_caller.rb', line 13

def options
  @options
end

Instance Method Details

#call(obj) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/localeapp/api_caller.rb', line 21

def call(obj)
  method, url = send("#{endpoint}_endpoint", options[:url_options] || {})
  Localeapp.debug("API CALL: #{method} #{url}")
  success = false
  while connection_attempts < max_connection_attempts
    sleep_if_retrying

    response = make_call(method, url)
    Localeapp.debug("RESPONSE: #{response.code}")

    fix_encoding(response)

    valid_response_codes = (200..207).to_a
    if valid_response_codes.include?(response.code.to_i)
      if options[:success]
        Localeapp.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
end