Class: Levelup::Requests::Base

Inherits:
Templates::DataParcel show all
Defined in:
lib/levelup/requests/base.rb

Overview

The class containing the base functionality of all requests.

Constant Summary collapse

ALLOWED_REQUEST_METHODS =
[:delete, :get, :post, :put]

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Templates::DataParcel

excluded?, #initialize

Constructor Details

This class inherits a constructor from Levelup::Templates::DataParcel

Class Method Details

.instance_variables_excluded_from_hashObject

default values to exclude from request hashes (header values)



34
35
36
37
# File 'lib/levelup/requests/base.rb', line 34

def self.instance_variables_excluded_from_hash
  @excluded ||= super.concat([:app_access_token, :merchant_access_token,
    :user_access_token])
end

Instance Method Details

#auth_typeObject

One of :none, :merchant, :app, :merchant_and_user

Raises:

  • (NotImplementedError)


8
9
10
# File 'lib/levelup/requests/base.rb', line 8

def auth_type
  raise NotImplementedError, 'Auth type not defined for request.'
end

#bodyObject

Returns the body of the request to send as a hash. By default, sends a hash of all assigned instance variables in the object.



14
15
16
# File 'lib/levelup/requests/base.rb', line 14

def body
  to_hash
end

#headersObject

Contains any additional headers passed in a request to the API. Builds the headers for a request out of a request object. Extending classes wishing to add additional headers should build their headers hash and return my_headers.merge(super)



22
23
24
25
26
27
28
29
30
31
# File 'lib/levelup/requests/base.rb', line 22

def headers
  headers = DEFAULT_HEADERS.dup

  auth = auth_header_value
  if auth
    headers['Authorization'] = auth
  end

  headers
end

#response_from_hashObject

Raises:

  • (NotImplementedError)


39
40
41
# File 'lib/levelup/requests/base.rb', line 39

def response_from_hash
  raise NotImplementedError, 'Response generator not defined.'
end

#send_to_api(method, endpoint) ⇒ Object

Makes a call by the specified method to the specified endpoint, sending this request object. If successful, builds a response object according to response_from_hash. If unsuccessful, simply returns an ErrorResponse.



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/levelup/requests/base.rb', line 46

def send_to_api(method, endpoint)
  unless ALLOWED_REQUEST_METHODS.include?(method)
    raise Errors::InvalidRequest, 'Attempted to send a request to'\
    " LevelUp API via invalid method #{method}"
  end

  response = HTTParty.public_send(method, endpoint,
    body: JSON.generate(body), headers: headers)

  if response.success?
    response_from_hash(response.parsed_response)
  else
    Responses::Error.new(response.headers, response.parsed_response,
      response.code)
  end
end