Class: Protocol::HTTP::Body::Buffered

Inherits:
Readable
  • Object
show all
Defined in:
lib/protocol/http/body/buffered.rb

Overview

A body which buffers all it’s contents.

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Readable

#call, #each, #join

Constructor Details

#initialize(chunks = [], length = nil) ⇒ Buffered

Returns a new instance of Buffered.



52
53
54
55
56
57
# File 'lib/protocol/http/body/buffered.rb', line 52

def initialize(chunks = [], length = nil)
	@chunks = chunks
	@length = length
	
	@index = 0
end

Class Method Details

.for(body) ⇒ Object



42
43
44
45
46
47
48
49
50
# File 'lib/protocol/http/body/buffered.rb', line 42

def self.for(body)
	chunks = []
	
	body.each do |chunk|
		chunks << chunk
	end
	
	self.new(chunks)
end

.wrap(body) ⇒ Readable?

Wraps an array into a buffered body.

Returns:

  • (Readable, nil)

    the wrapped body or nil if nil was given.



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/protocol/http/body/buffered.rb', line 30

def self.wrap(body)
	if body.is_a? Readable
		return body
	elsif body.is_a? Array
		return self.new(body)
	elsif body.is_a?(String)
		return self.new([body])
	elsif body
		return self.for(body)
	end
end

Instance Method Details

#close(error = nil) ⇒ Object



83
84
85
# File 'lib/protocol/http/body/buffered.rb', line 83

def close(error = nil)
	@chunks << nil
end

#empty?Boolean

Returns:

  • (Boolean)


67
68
69
# File 'lib/protocol/http/body/buffered.rb', line 67

def empty?
	@index >= @chunks.length
end

#finishObject



59
60
61
# File 'lib/protocol/http/body/buffered.rb', line 59

def finish
	self
end

#inspectObject



91
92
93
# File 'lib/protocol/http/body/buffered.rb', line 91

def inspect
	"\#<#{self.class} #{@chunks.count} chunks, #{self.length} bytes>"
end

#lengthObject



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

def length
	@length ||= @chunks.inject(0) {|sum, chunk| sum + chunk.bytesize}
end

#readObject



71
72
73
74
75
76
77
# File 'lib/protocol/http/body/buffered.rb', line 71

def read
	if chunk = @chunks[@index]
		@index += 1
		
		return chunk.dup
	end
end

#rewindObject



87
88
89
# File 'lib/protocol/http/body/buffered.rb', line 87

def rewind
	@index = 0
end

#write(chunk) ⇒ Object



79
80
81
# File 'lib/protocol/http/body/buffered.rb', line 79

def write(chunk)
	@chunks << chunk
end