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