Class: Peddler::Response
- Inherits:
-
SimpleDelegator
- Object
- SimpleDelegator
- Peddler::Response
- Extended by:
- Forwardable
- Defined in:
- lib/peddler/response.rb
Overview
Wraps HTTP::Response to allow custom parsing
Delegates all unimplemented methods to the wrapped HTTP::Response object.
Instance Attribute Summary collapse
-
#parser ⇒ nil, #parse
readonly
Optional parser for the response.
Class Method Summary collapse
-
.wrap(response, parser: nil) ⇒ Response
Wraps an HTTP response with error checking.
Instance Method Summary collapse
-
#dig(*key) ⇒ Object
Delegates to the Hash returned by #to_h to extract a nested value specified by the sequence of keys.
-
#initialize(http_response, parser: nil) ⇒ Response
constructor
Creates a new Response wrapper.
-
#parsable? ⇒ Boolean
Whether this response can be parsed into typed objects.
-
#parse ⇒ Object
Parses the response with typed Data objects.
-
#raise_for_status! ⇒ void
Raises an error if the HTTP response status indicates failure.
-
#to_h ⇒ Hash
Converts the response body to a Hash.
Constructor Details
#initialize(http_response, parser: nil) ⇒ Response
Creates a new Response wrapper
42 43 44 45 |
# File 'lib/peddler/response.rb', line 42 def initialize(http_response, parser: nil) super(http_response) @parser = parser end |
Instance Attribute Details
#parser ⇒ nil, #parse (readonly)
Returns Optional parser for the response.
14 15 16 |
# File 'lib/peddler/response.rb', line 14 def parser @parser end |
Class Method Details
.wrap(response, parser: nil) ⇒ Response
Wraps an HTTP response with error checking
31 32 33 34 35 |
# File 'lib/peddler/response.rb', line 31 def wrap(response, parser: nil) wrapped = new(response, parser:) wrapped.raise_for_status! wrapped end |
Instance Method Details
#dig(*key) ⇒ Object
Delegates to the Hash returned by #to_h to extract a nested value specified by the sequence of keys
22 |
# File 'lib/peddler/response.rb', line 22 def_delegator :to_h, :dig |
#parsable? ⇒ Boolean
Returns Whether this response can be parsed into typed objects.
48 49 50 |
# File 'lib/peddler/response.rb', line 48 def parsable? !parser.nil? end |
#parse ⇒ Object
Parses the response with typed Data objects
55 56 57 |
# File 'lib/peddler/response.rb', line 55 def parse parsable? ? parser.call.parse(to_h) : to_h end |
#raise_for_status! ⇒ void
This method returns an undefined value.
Raises an error if the HTTP response status indicates failure
70 71 72 73 74 75 |
# File 'lib/peddler/response.rb', line 70 def raise_for_status! return if status < 400 error = Error.build(__getobj__) raise error || Error.new(status, __getobj__) end |
#to_h ⇒ Hash
Converts the response body to a Hash
62 63 64 |
# File 'lib/peddler/response.rb', line 62 def to_h __getobj__.parse end |