A streamable response body, also easily converted into a string
The connection object used to make the corresponding request.
@return [HTTP::Connection]
# File lib/http/response/body.rb, line 18 def initialize(stream, encoding = Encoding::BINARY) @stream = stream @connection = stream.is_a?(Inflater) ? stream.connection : stream @streaming = nil @contents = nil @encoding = encoding end
Iterate over the body, allowing it to be enumerable
# File lib/http/response/body.rb, line 33 def each while (chunk = readpartial) yield chunk end end # @return [String] eagerly consume the entire body as a string 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
Easier to interpret string inspect
# File lib/http/response/body.rb, line 75 def inspect "#<#{self.class}:#{object_id.to_s(16)} @streaming=#{!!@streaming}>" end
(see HTTP::Client#readpartial)
# File lib/http/response/body.rb, line 27 def readpartial(*args) stream! @stream.readpartial(*args) end
Assert that the body is actively being streamed
# File lib/http/response/body.rb, line 69 def stream! raise StateError, "body has already been consumed" if @streaming == false @streaming = true end