Class: AxTrack::Resource

Inherits:
Object
  • Object
show all
Defined in:
lib/ax_track/resource.rb

Direct Known Subclasses

AssetResource, TrackerResource

Constant Summary collapse

ApiError =
Class.new(StandardError)
BadRequestError =
Class.new(ApiError)
UnauthorizedError =
Class.new(ApiError)
ForbiddenError =
Class.new(ApiError)
ApiRequestsQuotaReachedError =
Class.new(ApiError)
NotFoundError =
Class.new(ApiError)
UnprocessableEntityError =
Class.new(ApiError)
HTTP_OK_CODE =
200
HTTP_BAD_REQUEST_CODE =
400
HTTP_UNAUTHORIZED_CODE =
401
HTTP_FORBIDDEN_CODE =
403
HTTP_NOT_FOUND_CODE =
404
HTTP_UNPROCESSABLE_ENTITY_CODE =
429

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client) ⇒ Resource

Returns a new instance of Resource.



21
22
23
24
# File 'lib/ax_track/resource.rb', line 21

def initialize(client)
  @client = client
  @response = nil
end

Instance Attribute Details

#clientObject (readonly)

Returns the value of attribute client.



3
4
5
# File 'lib/ax_track/resource.rb', line 3

def client
  @client
end

#responseObject (readonly)

Returns the value of attribute response.



3
4
5
# File 'lib/ax_track/resource.rb', line 3

def response
  @response
end

Instance Method Details

#error_class(status) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/ax_track/resource.rb', line 44

def error_class(status)
  case status
  when HTTP_BAD_REQUEST_CODE
    BadRequestError
  when HTTP_UNAUTHORIZED_CODE
    UnauthorizedError
  when HTTP_NOT_FOUND_CODE, HTTP_FORBIDDEN_CODE
    NotFoundError
  when HTTP_UNPROCESSABLE_ENTITY_CODE
    UnprocessableEntityError
  else
    ApiError
  end
end

#request(http_method: :get, endpoint:, headers: {}, params: {}, body: {}, result_subset: nil) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/ax_track/resource.rb', line 26

def request(http_method: :get, endpoint:, headers: {}, params: {}, body: {}, result_subset: nil)
  raise "Client not defined" unless defined? @client
  endpoint = endpoint + "/" unless endpoint[-1] == "/"

  if body.keys.include?(:picture)
    body[:picture] = Faraday::FilePart.new(body[:picture].url, body[:picture].content_type, body[:picture].filename)
  end

  # client.connection['headers']['Content-Type'] = 'multipart/form-data' if body.key? :picture
  @response = client.connection.public_send(http_method, endpoint, params.merge(body))

  unless response_successful?
    raise error_class(response.status), "Code: #{response.status}, response: #{response.reason_phrase}"
  end

  result_subset ? response[result_subset.to_s] : response
end

#response_successful?Boolean

Returns:

  • (Boolean)


59
60
61
# File 'lib/ax_track/resource.rb', line 59

def response_successful?
  response.status == HTTP_OK_CODE
end