Class: Peddler::Response

Inherits:
SimpleDelegator
  • Object
show all
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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(http_response, parser: nil) ⇒ Response

Creates a new Response wrapper

Parameters:

  • http_response (HTTP::Response)

    The HTTP response to wrap

  • parser (nil, #parse) (defaults to: nil)

    Optional parser for the response



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

#parsernil, #parse (readonly)

Returns Optional parser for the response.

Returns:

  • (nil, #parse)

    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

Parameters:

  • response (HTTP::Response)

    The HTTP response to wrap

  • parser (nil, #parse) (defaults to: nil)

    Optional parser for the response

Returns:

Raises:



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

Parameters:

  • key (String)

    one or more keys

See Also:



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.

Returns:

  • (Boolean)

    Whether this response can be parsed into typed objects



48
49
50
# File 'lib/peddler/response.rb', line 48

def parsable?
  !parser.nil?
end

#parseObject

Parses the response with typed Data objects

Returns:

  • (Object)

    Parsed response with type information, or Hash if no parser



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

Raises:



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_hHash

Converts the response body to a Hash

Returns:

  • (Hash)


62
63
64
# File 'lib/peddler/response.rb', line 62

def to_h
  __getobj__.parse
end