Module: Protocol::HTTP::Body::Reader

Included in:
Request, Response
Defined in:
lib/protocol/http/body/reader.rb

Overview

General operations for interacting with a request or response body.

Instance Method Summary collapse

Instance Method Details

#body?Boolean

Whether there is a body?

Returns:

  • (Boolean)


63
64
65
# File 'lib/protocol/http/body/reader.rb', line 63

def body?
  @body and !@body.empty?
end

#close(error = nil) ⇒ Object

Close the connection as quickly as possible. Discards body. May close the underlying connection if necessary to terminate the stream.



55
56
57
58
59
60
# File 'lib/protocol/http/body/reader.rb', line 55

def close(error = nil)
  if @body
    @body.close(error)
    @body = nil
  end
end

#each {|String| ... } ⇒ Object

Read chunks from the body.

Yields:

  • (String)

    read chunks from the body.



14
15
16
17
18
19
# File 'lib/protocol/http/body/reader.rb', line 14

def each(&block)
  if @body
    @body.each(&block)
    @body = nil
  end
end

#finishBuffered

Gracefully finish reading the body. This will buffer the remainder of the body.

Returns:

  • (Buffered)

    buffers the entire body.



34
35
36
37
38
39
40
41
# File 'lib/protocol/http/body/reader.rb', line 34

def finish
  if @body
    body = @body.finish
    @body = nil
    
    return body
  end
end

#readString

Reads the entire request/response body.

Returns:

  • (String)

    the entire body as a string.



23
24
25
26
27
28
29
30
# File 'lib/protocol/http/body/reader.rb', line 23

def read
  if @body
    buffer = @body.join
    @body = nil
    
    return buffer
  end
end

#save(path, mode = ::File::WRONLY|::File::CREAT|::File::TRUNC, **options) ⇒ Object

Write the body of the response to the given file path.



44
45
46
47
48
49
50
51
52
# File 'lib/protocol/http/body/reader.rb', line 44

def save(path, mode = ::File::WRONLY|::File::CREAT|::File::TRUNC, **options)
  if @body
    ::File.open(path, mode, **options) do |file|
      self.each do |chunk|
        file.write(chunk)
      end
    end
  end
end