Class: Restspec::Endpoints::Response

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

Overview

A response is a representation of the triad returned by the API calls. They represent the status code, the headers and the response's body.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(code, headers, raw_body) ⇒ Response

Returns a new instance of Response.



11
12
13
14
15
# File 'lib/restspec/endpoints/response.rb', line 11

def initialize(code, headers, raw_body)
  self.headers = headers
  self.code = code
  self.raw_body = raw_body
end

Instance Attribute Details

#codeObject

Returns the value of attribute code.



9
10
11
# File 'lib/restspec/endpoints/response.rb', line 9

def code
  @code
end

#endpointObject

Returns the value of attribute endpoint.



9
10
11
# File 'lib/restspec/endpoints/response.rb', line 9

def endpoint
  @endpoint
end

#headersObject

Returns the value of attribute headers.



9
10
11
# File 'lib/restspec/endpoints/response.rb', line 9

def headers
  @headers
end

#raw_bodyObject

Returns the value of attribute raw_body.



9
10
11
# File 'lib/restspec/endpoints/response.rb', line 9

def raw_body
  @raw_body
end

Instance Method Details

#bodyObject



51
52
53
# File 'lib/restspec/endpoints/response.rb', line 51

def body
  @body ||= read_body
end

#parsed_bodyObject



43
44
45
46
47
48
49
# File 'lib/restspec/endpoints/response.rb', line 43

def parsed_body
  @parsed_body ||= begin
    JSON.parse(raw_body)
  rescue JSON::ParserError => e
    raw_body
  end
end

#read_body(value = parsed_body) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/restspec/endpoints/response.rb', line 26

def read_body(value = parsed_body)
  case value
  when Array
    value.map { |item| read_body(item) }
  when Hash
    Values::SuperHash.new(value).tap do |super_hash|
      super_hash.find do |key, value|
        if value.class == Array
          super_hash[key] = read_body(value)
        end
      end
    end
  else
    value
  end
end

#to_sObject



17
18
19
20
21
22
23
24
# File 'lib/restspec/endpoints/response.rb', line 17

def to_s
  if endpoint.present?
    url = endpoint.executed_url || endpoint.full_path
    "[#{endpoint.method.upcase} to #{url}]"
  else
    raw_body
  end
end