Class: HTTP::Response::Body
- Inherits:
-
Object
- Object
- HTTP::Response::Body
- 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
-
#connection ⇒ HTTP::Connection
readonly
The connection object used to make the corresponding request.
Instance Method Summary collapse
-
#each ⇒ Object
Iterate over the body, allowing it to be enumerable.
-
#initialize(connection, stream, encoding = Encoding::BINARY) ⇒ Body
constructor
A new instance of Body.
-
#inspect ⇒ Object
Easier to interpret string inspect.
- #readpartial(*args) ⇒ Object
-
#stream! ⇒ Object
Assert that the body is actively being streamed.
-
#to_s ⇒ String
(also: #to_str)
Eagerly consume the entire body as a string.
Constructor Details
#initialize(connection, stream, encoding = Encoding::BINARY) ⇒ Body
Returns a new instance of Body.
18 19 20 21 22 23 24 |
# File 'lib/http/response/body.rb', line 18 def initialize(connection, stream, encoding = Encoding::BINARY) @connection = connection @streaming = nil @contents = nil @stream = stream @encoding = encoding end |
Instance Attribute Details
#connection ⇒ HTTP::Connection (readonly)
The connection object used to make the corresponding request.
16 17 18 |
# File 'lib/http/response/body.rb', line 16 def connection @connection end |
Instance Method Details
#each ⇒ Object
Iterate over the body, allowing it to be enumerable
33 34 35 36 37 |
# File 'lib/http/response/body.rb', line 33 def each while (chunk = readpartial) yield chunk end end |
#inspect ⇒ Object
Easier to interpret string inspect
75 76 77 |
# File 'lib/http/response/body.rb', line 75 def inspect "#<#{self.class}:#{object_id.to_s(16)} @streaming=#{!!@streaming}>" end |
#readpartial(*args) ⇒ Object
27 28 29 30 |
# File 'lib/http/response/body.rb', line 27 def readpartial(*args) stream! @stream.readpartial(*args) end |
#stream! ⇒ Object
Assert that the body is actively being streamed
69 70 71 72 |
# File 'lib/http/response/body.rb', line 69 def stream! raise StateError, "body has already been consumed" if @streaming == false @streaming = true end |
#to_s ⇒ String Also known as: to_str
Returns eagerly consume the entire body as a string.
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/http/response/body.rb', line 40 def to_s return @contents if @contents raise StateError, "body is being streamed" unless @streaming.nil? # see issue 312 begin encoding = Encoding.find @encoding rescue ArgumentError encoding = Encoding::BINARY end begin @streaming = false @contents = String.new("").force_encoding(encoding) while (chunk = @stream.readpartial) @contents << chunk.force_encoding(encoding) end rescue @contents = nil raise end @contents end |