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(request:, body:, headers:, status:, message:) ⇒ Response

Returns a new instance of Response.



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

def initialize(request:, body:, headers:, status:, message:)
  @request, @headers = request, headers
  @status, @message = status, 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”)



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

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

#bytesObject



38
39
40
# File 'lib/simple/http/response.rb', line 38

def bytes
  @original_body&.byte_size || 0
end

#contentObject

evaluate and potentially parse response



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

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:



48
49
50
51
52
# File 'lib/simple/http/response.rb', line 48

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

  content
end

#media_typeObject

e.g “text/plain”



26
27
28
# File 'lib/simple/http/response.rb', line 26

def media_type
  @body_builder.media_type
end

#to_sObject



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

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