Class: HTTP::Response::Body

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Enumerable
Defined in:
lib/http/response/body.rb

Overview

A streamable response body, also easily converted into a string

Instance Method Summary collapse

Constructor Details

#initialize(client) ⇒ Body

Returns a new instance of Body.



12
13
14
15
16
# File 'lib/http/response/body.rb', line 12

def initialize(client)
  @client       = client
  @streaming    = nil
  @contents     = nil
end

Instance Method Details

#eachObject

Iterate over the body, allowing it to be enumerable



25
26
27
28
29
# File 'lib/http/response/body.rb', line 25

def each
  while (chunk = readpartial)
    yield chunk
  end
end

#inspectObject

Easier to interpret string inspect



59
60
61
# File 'lib/http/response/body.rb', line 59

def inspect
  "#<#{self.class}:#{object_id.to_s(16)} @streaming=#{!!@streaming}>"
end

#readpartial(*args) ⇒ Object



19
20
21
22
# File 'lib/http/response/body.rb', line 19

def readpartial(*args)
  stream!
  @client.readpartial(*args)
end

#stream!Object

Assert that the body is actively being streamed



53
54
55
56
# File 'lib/http/response/body.rb', line 53

def stream!
  fail StateError, "body has already been consumed" if @streaming == false
  @streaming = true
end

#to_sString Also known as: to_str

Returns eagerly consume the entire body as a string.

Returns:

  • (String)

    eagerly consume the entire body as a string



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/http/response/body.rb', line 32

def to_s
  return @contents if @contents

  fail StateError, "body is being streamed" unless @streaming.nil?

  begin
    @streaming = false
    @contents = "".force_encoding(Encoding::UTF_8)
    while (chunk = @client.readpartial)
      @contents << chunk.force_encoding(Encoding::ASCII_8BIT)
    end
  rescue
    @contents = nil
    raise
  end

  @contents
end