Class: ApiResource::Response

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(response) ⇒ Response

Constructor

Parameters:

  • response (HttpClient::Response)
  • format (ApiResource::Format)

    Decoder



22
23
24
25
# File 'lib/api_resource/response.rb', line 22

def initialize(response)
  @body = self.parse_body(response)
  @headers = response.try(:headers) || {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args, &block) ⇒ Mixed (protected)

Proxy method missing to the body

Parameters:

  • meth (Symbol)

    Method called

  • *args (Array<Mixed>)

    Args passed

  • &block (Proc)

    Block passed

Returns:

  • (Mixed)


88
89
90
# File 'lib/api_resource/response.rb', line 88

def method_missing(meth, *args, &block)
  @body.__send__(meth, *args, &block)
end

Instance Attribute Details

#bodyObject

Returns the value of attribute body.



4
5
6
# File 'lib/api_resource/response.rb', line 4

def body
  @body
end

#headersObject (readonly)

Returns the value of attribute headers.



5
6
7
# File 'lib/api_resource/response.rb', line 5

def headers
  @headers
end

Instance Method Details

#is_a?(klass) ⇒ Boolean

We typically treat the response as just a wrapper for an Array or a Hash and use is_a? to determine what kind of response we have. So to keep that consistent, #is_a? returns true if the body is a descendant of the class as well

Parameters:

  • klass (Class)

Returns:

  • (Boolean)


36
37
38
# File 'lib/api_resource/response.rb', line 36

def is_a?(klass)
  super || @body.is_a?(klass)
end

#marshal_dumpArray<Hash>

Implementation of marshal_dump

Returns:

  • (Array<Hash>)

    The data to dump



44
45
46
# File 'lib/api_resource/response.rb', line 44

def marshal_dump
  [@body, @headers]
end

#marshal_load(args) ⇒ Response

Implementation of marshal load

Parameters:

  • args (Array)

    Array of dumped data

Returns:



53
54
55
56
# File 'lib/api_resource/response.rb', line 53

def marshal_load(args)
  @body, @headers = args
  self
end

#to_aryApiResource::Response

Return ourself cloned with the body wrapped as an array

Examples:

resp = ApiResource::Response.new(response, format)
resp.body # => {'a' => 'b'}

array = Array.wrap(resp)
array.body # => [{'a' => 'b'}]

array.response == resp.response # true!

Returns:



72
73
74
75
76
# File 'lib/api_resource/response.rb', line 72

def to_ary
  klone = self.dup
  klone.body = Array.wrap(self.body)
  klone
end