Class: Simple::HTTP::Response

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

Constant Summary collapse

BodyBuilder =
Simple::HTTP::BodyBuilder

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(body:, headers:, status:, message:) ⇒ Response

Returns a new instance of Response.



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/simple/http/response.rb', line 12

def initialize(body:, headers:, status:, message:)
  @headers = headers
  @status = status
  @message = message
  @original_body = body

  # adjust encoding on original_body
  @body_builder = BodyBuilder.new(headers["Content-Type"])

  if @original_body && (charset = @body_builder.charset)
    @original_body.force_encoding(charset)
  end
end

Instance Attribute Details

#headersObject (readonly)

Returns the value of attribute headers.



9
10
11
# File 'lib/simple/http/response.rb', line 9

def headers
  @headers
end

#messageObject (readonly)

Returns the value of attribute message.



8
9
10
# File 'lib/simple/http/response.rb', line 8

def message
  @message
end

#original_bodyObject (readonly)

Returns the value of attribute original_body.



10
11
12
# File 'lib/simple/http/response.rb', line 10

def original_body
  @original_body
end

#requestObject (readonly)

Returns the value of attribute request.



6
7
8
# File 'lib/simple/http/response.rb', line 6

def request
  @request
end

#statusObject (readonly)

Returns the value of attribute status.



7
8
9
# File 'lib/simple/http/response.rb', line 7

def status
  @status
end

Instance Method Details

#bodyObject

returns the body

This method reencodes the text body into UTF-8. Non-text bodies should be encoded as ASCII-8BIT (a.k.a. “BINARY”)



43
44
45
# File 'lib/simple/http/response.rb', line 43

def body
  @body ||= @body_builder.reencode(@original_body)
end

#bytesObject



47
48
49
# File 'lib/simple/http/response.rb', line 47

def bytes
  @original_body&.byte_size || 0
end

#contentObject

evaluate and potentially parse response



64
65
66
67
68
69
70
71
# File 'lib/simple/http/response.rb', line 64

def content
  case media_type
  when "application/json"
    JSON.parse(body) unless body.empty?
  else
    body
  end
end

#content!Object

evaluate and potentially parses response body. raises an Simple::Http::Error if the result code is not a 2xx

Raises:



57
58
59
60
61
# File 'lib/simple/http/response.rb', line 57

def content!
  raise Error, self unless status >= 200 && status <= 299

  content
end

#media_typeObject

e.g “text/plain”



35
36
37
# File 'lib/simple/http/response.rb', line 35

def media_type
  @body_builder.media_type
end

#to_sObject



51
52
53
# File 'lib/simple/http/response.rb', line 51

def to_s
  "#{status} #{message.gsub(/\s+$/, "")} (#{bytes} byte)"
end