Class: HTTP::Response::Body

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Enumerable
Defined in:
lib/http/response/body.rb

Overview

A streamable response body, also easily converted into a string

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(stream, encoding: Encoding::BINARY) ⇒ Body

Returns a new instance of Body.



19
20
21
22
23
24
25
# File 'lib/http/response/body.rb', line 19

def initialize(stream, encoding: Encoding::BINARY)
  @stream     = stream
  @connection = stream.is_a?(Inflater) ? stream.connection : stream
  @streaming  = nil
  @contents   = nil
  @encoding   = find_encoding(encoding)
end

Instance Attribute Details

#connectionHTTP::Connection (readonly)

The connection object used to make the corresponding request.

Returns:



17
18
19
# File 'lib/http/response/body.rb', line 17

def connection
  @connection
end

Instance Method Details

#eachObject

Iterate over the body, allowing it to be enumerable



36
37
38
39
40
# File 'lib/http/response/body.rb', line 36

def each
  while (chunk = readpartial)
    yield chunk
  end
end

#inspectObject

Easier to interpret string inspect



73
74
75
# File 'lib/http/response/body.rb', line 73

def inspect
  "#<#{self.class}:#{object_id.to_s(16)} @streaming=#{!!@streaming}>"
end

#readpartial(*args) ⇒ Object



28
29
30
31
32
33
# File 'lib/http/response/body.rb', line 28

def readpartial(*args)
  stream!
  chunk = @stream.readpartial(*args)

  String.new(chunk, encoding: @encoding) if chunk
end

#stream!Object

Assert that the body is actively being streamed

Raises:



66
67
68
69
70
# File 'lib/http/response/body.rb', line 66

def stream!
  raise StateError, "body has already been consumed" if @streaming == false

  @streaming = true
end

#to_sString Also known as: to_str

Returns eagerly consume the entire body as a string.

Returns:

  • (String)

    eagerly consume the entire body as a string

Raises:



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/http/response/body.rb', line 43

def to_s
  return @contents if @contents

  raise StateError, "body is being streamed" unless @streaming.nil?

  begin
    @streaming  = false
    @contents   = String.new("", encoding: @encoding)

    while (chunk = @stream.readpartial)
      @contents << String.new(chunk, encoding: @encoding)
      chunk = nil # deallocate string
    end
  rescue
    @contents = nil
    raise
  end

  @contents
end