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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#parser#call

Returns:

  • (#call)


68
69
70
# File 'lib/peddler/response.rb', line 68

def parser
  @parser
end

Class Method Details

.decorate(response, parser: nil) ⇒ ResponseDecorator

Decorates an HTTP::Response with error handling

Parameters:

  • response (HTTP::Response)
  • parser (nil, #call) (defaults to: nil)

    (if any)

Returns:

  • (ResponseDecorator)

Raises:



55
56
57
58
59
60
61
62
63
64
# File 'lib/peddler/response.rb', line 55

def decorate(response, parser: nil)
  if response.status.client_error?
    error = Error.build(response)
    error ? raise(error) : raise(Error.new("Unexpected status code #{response.status.code}", response))
  end

  new(response).tap do |decorator|
    decorator.parser = parser
  end
end

Instance Method Details

#dig(*key) ⇒ Object

Delegates to the Hash returned by ResponseDecorator#to_h to extract a nested value specified by the sequence of keys

Parameters:

  • key (String)

    one or more keys

See Also:



46
# File 'lib/peddler/response.rb', line 46

def_delegator :to_h, :dig

#parseObject



70
71
72
# File 'lib/peddler/response.rb', line 70

def parse
  parser ? parser.call(__getobj__) : __getobj__.parse
end

#to_hHash

Converts the response body to a Hash

Returns:

  • (Hash)


77
78
79
# File 'lib/peddler/response.rb', line 77

def to_h
  (parser && parser.respond_to?(:to_h) ? parser : parse).to_h
end