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.

This module is included in both Request and Response.

Instance Method Summary collapse

Instance Method Details

#body?Boolean

Whether there is a body?

Returns:

  • (Boolean)


98
99
100
# File 'lib/protocol/http/body/reader.rb', line 98

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

#buffered!Object

Buffer the entire request/response body.



61
62
63
64
65
66
67
68
# File 'lib/protocol/http/body/reader.rb', line 61

def buffered!
	if @body
		@body = @body.finish
	end
	
	# TODO Should this return @body instead? It seems more useful.
	return self
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.



88
89
90
91
92
93
# File 'lib/protocol/http/body/reader.rb', line 88

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

#discardObject

Discard the body as efficiently as possible.



49
50
51
52
53
54
55
56
# File 'lib/protocol/http/body/reader.rb', line 49

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

#each(&block) ⇒ Object

Read chunks from the body.



17
18
19
20
21
22
# File 'lib/protocol/http/body/reader.rb', line 17

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

#finishObject

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



39
40
41
42
43
44
45
46
# File 'lib/protocol/http/body/reader.rb', line 39

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

#readObject

Reads the entire request/response body.



27
28
29
30
31
32
33
34
# File 'lib/protocol/http/body/reader.rb', line 27

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.



75
76
77
78
79
80
81
82
83
# File 'lib/protocol/http/body/reader.rb', line 75

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