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.



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

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

Instance Method Details

#eachObject

Iterate over the body, allowing it to be enumerable



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

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

#inspectObject

Easier to interpret string inspect



57
58
59
# File 'lib/http/response/body.rb', line 57

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

#readpartial(length = nil) ⇒ Object

Read up to length bytes, but return any data that’s available



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

def readpartial(length = nil)
  stream!
  @client.readpartial(length)
end

#stream!Object

Assert that the body is actively being streamed



51
52
53
54
# File 'lib/http/response/body.rb', line 51

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

#to_sObject Also known as: to_str

Eagerly consume the entire body as a string



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

def to_s
  return @contents if @contents
  fail StateError, 'body is being streamed' unless @streaming.nil?

  begin
    @streaming = false
    @contents = ''
    while (chunk = @client.readpartial)
      @contents << chunk
    end
  rescue
    @contents = nil
    raise
  end

  @contents
end