class HTTP::Response::Body
A streamable response body, also easily converted into a string
Attributes
The connection object used to make the corresponding request.
@return [HTTP::Connection]
Public Class Methods
Source
# 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
Public Instance Methods
Source
# File lib/http/response/body.rb, line 36 def each while (chunk = readpartial) yield chunk end end
Iterate over the body, allowing it to be enumerable
Source
# File lib/http/response/body.rb, line 73 def inspect "#<#{self.class}:#{object_id.to_s(16)} @streaming=#{!!@streaming}>" end
Easier to interpret string inspect
Source
# File lib/http/response/body.rb, line 28 def readpartial(*args) stream! chunk = @stream.readpartial(*args) String.new(chunk, :encoding => @encoding) if chunk end
(see HTTP::Client#readpartial)
Source
# File lib/http/response/body.rb, line 66 def stream! raise StateError, "body has already been consumed" if @streaming == false @streaming = true end
Assert that the body is actively being streamed
Source
# 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
@return [String] eagerly consume the entire body as a string
Also aliased as: to_str
Private Instance Methods
Source
# File lib/http/response/body.rb, line 80 def find_encoding(encoding) Encoding.find encoding rescue ArgumentError Encoding::BINARY end
Retrieve encoding by name. If encoding cannot be found, default to binary.