Class: Truepill::Response
- Inherits:
-
Object
- Object
- Truepill::Response
- 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
-
#response ⇒ Object
readonly
Returns the value of attribute response.
Instance Method Summary collapse
-
#data ⇒ Object
Parsed response (e.g. Hash version of json received back).
- #error? ⇒ Boolean
- #error_message ⇒ Object
- #errors ⇒ Object
-
#initialize(response) ⇒ Response
constructor
A new instance of Response.
- #success? ⇒ Boolean
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
#response ⇒ Object (readonly)
Returns the value of attribute response.
12 13 14 |
# File 'lib/truepill/response.rb', line 12 def response @response end |
Instance Method Details
#data ⇒ Object
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
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_message ⇒ Object
38 39 40 |
# File 'lib/truepill/response.rb', line 38 def errors&.join(', ') end |
#errors ⇒ Object
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
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 |