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, encoding = Encoding::BINARY) ⇒ Body

Returns a new instance of Body.



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

def initialize(client, encoding = Encoding::BINARY)
  @client    = client
  @streaming = nil
  @contents  = nil
  @encoding  = encoding
end

Instance Method Details

#eachObject

Iterate over the body, allowing it to be enumerable



27
28
29
30
31
# File 'lib/http/response/body.rb', line 27

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

#inspectObject

Easier to interpret string inspect



69
70
71
# File 'lib/http/response/body.rb', line 69

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

#readpartial(*args) ⇒ Object



21
22
23
24
# File 'lib/http/response/body.rb', line 21

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

#stream!Object

Assert that the body is actively being streamed

Raises:



63
64
65
66
# File 'lib/http/response/body.rb', line 63

def stream!
  raise 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

Raises:



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/http/response/body.rb', line 34

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 = @client.readpartial)
      @contents << chunk.force_encoding(encoding)
    end
  rescue
    @contents = nil
    raise
  end

  @contents
end