Class: Truepill::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/truepill/response.rb

Overview

Truepill Response class

Encapsulates a parsed json response from Truepill's API with methods for things like HTTP status codes, etc.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(response) ⇒ Response

Returns a new instance of Response.



15
16
17
# File 'lib/truepill/response.rb', line 15

def initialize(response)
  @response = response
end

Instance Attribute Details

#responseObject (readonly)

Returns the value of attribute response.



12
13
14
# File 'lib/truepill/response.rb', line 12

def response
  @response
end

Instance Method Details

#dataObject

Parsed response (e.g. Hash version of json received back)



46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/truepill/response.rb', line 46

def data
  if parsed_response.is_a?(Hash)
    parsed_response&.with_indifferent_access
  elsif parsed_response.is_a?(Array)
    parsed_response.map(&:with_indifferent_access)
  else
    parsed_response
  end
rescue JSON::ParserError
  # if the server sends an invalid response
  body
end

#error?Boolean

Returns:

  • (Boolean)


25
26
27
28
29
# File 'lib/truepill/response.rb', line 25

def error?
  code.to_i / 100 != 2 || data[:statusCode] == 400
rescue => e
  true
end

#error_messageObject



38
39
40
# File 'lib/truepill/response.rb', line 38

def error_message
  errors&.join(', ')
end

#errorsObject



31
32
33
34
35
36
# File 'lib/truepill/response.rb', line 31

def errors
  return ["Invalid response: #{body}"] unless data.is_a?(Hash)
  data[:validation_errors]&.map do |error_data|
    "#{error_data[:key]} #{error_data[:message]}"
  end
end

#success?Boolean

Returns:

  • (Boolean)


19
20
21
22
23
# File 'lib/truepill/response.rb', line 19

def success?
  %w(success processed).include?(data[:status]) || !error?
rescue => e
  false
end