class HTTP::Response::Body
A streamable response body, also easily converted into a string
Public Class Methods
new(client, encoding = Encoding::BINARY)
click to toggle source
# File lib/http/response/body.rb, line 12 def initialize(client, encoding = Encoding::BINARY) @client = client @streaming = nil @contents = nil @encoding = encoding end
Public Instance Methods
each()
click to toggle source
Iterate over the body, allowing it to be enumerable
# File lib/http/response/body.rb, line 26 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 = "".force_encoding(encoding) while (chunk = @client.readpartial) @contents << chunk.force_encoding(encoding) end rescue @contents = nil raise end @contents end
inspect()
click to toggle source
Easier to interpret string inspect
# File lib/http/response/body.rb, line 67 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 20 def readpartial(*args) stream! @client.readpartial(*args) end
stream!()
click to toggle source
Assert that the body is actively being streamed
# File lib/http/response/body.rb, line 61 def stream! raise StateError, "body has already been consumed" if @streaming == false @streaming = true end