Class: Protocol::Rack::Input

Inherits:
Object
  • Object
show all
Includes:
HTTP::Body::Stream::Reader
Defined in:
lib/protocol/rack/input.rb

Overview

Wraps a streaming input body into the interface required by `rack.input`.

The input stream is an `IO`-like object which contains the raw HTTP POST data. When applicable, its external encoding must be `ASCII-8BIT` and it must be opened in binary mode, for Ruby 1.9 compatibility. The input stream must respond to `gets`, `each`, `read` and `rewind`.

This implementation is not always rewindable, to avoid buffering the input when handling large uploads. See Rewindable for more details.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(body) ⇒ Input

Initialize the input wrapper.



36
37
38
39
40
41
# File 'lib/protocol/rack/input.rb', line 36

def initialize(body)
	@body = body
	
	# Will hold remaining data in `#read`.
	@buffer = nil
end

Instance Attribute Details

#bodyObject (readonly)

The input body.



45
46
47
# File 'lib/protocol/rack/input.rb', line 45

def body
  @body
end

Instance Method Details

#close(error = nil) ⇒ Object

Close the input and output bodies.



76
77
78
79
80
81
82
83
# File 'lib/protocol/rack/input.rb', line 76

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

#closed?Boolean

Whether the stream has been closed.

Returns:

  • (Boolean)


104
105
106
# File 'lib/protocol/rack/input.rb', line 104

def closed?
	@body.nil?
end

#each(&block) ⇒ Object

Enumerate chunks of the request body.



50
51
52
53
54
55
56
# File 'lib/protocol/rack/input.rb', line 50

def each(&block)
	return to_enum unless block_given?
	
	while chunk = gets
		yield chunk
	end
end

#empty?Boolean

Whether there are any output chunks remaining?

Returns:

  • (Boolean)


109
110
111
# File 'lib/protocol/rack/input.rb', line 109

def empty?
	@output.empty?
end

#getsObject

Read the next chunk of data from the input stream.

`gets` must be called without arguments and return a `String`, or `nil` when the input stream has no more data.



65
66
67
68
69
70
71
72
73
# File 'lib/protocol/rack/input.rb', line 65

def gets
	if @buffer.nil?
		return read_next
	else
		buffer = @buffer
		@buffer = nil
		return buffer
	end
end

#rewindObject

Rewind the input stream back to the start.

`rewind` must be called without arguments. It rewinds the input stream back to the beginning. It must not raise Errno::ESPIPE: that is, it may not be a pipe or a socket. Therefore, handler developers must buffer the input data into some rewindable object if the underlying input stream is not rewindable.



90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/protocol/rack/input.rb', line 90

def rewind
	if @body and @body.respond_to?(:rewind)
		# If the body is not rewindable, this will fail.
		@body.rewind
		@buffer = nil
		@finished = false
		
		return true
	end
	
	return false
end