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

#close, #each, #join

Constructor Details

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

Returns a new instance of Buffered.



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

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

Class Method Details

.for(body) ⇒ Object



46
47
48
49
50
51
52
53
54
# File 'lib/protocol/http/body/buffered.rb', line 46

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.



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

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

#digestObject



64
65
66
67
68
69
70
71
# File 'lib/protocol/http/body/buffered.rb', line 64

def digest
  if @digest.nil?
    @digest = Digest::SHA256.new
    @chunks.each{|chunk| @digest.update(chunk)}
  end
  
  @digest.hexdigest
end

#empty?Boolean

Returns:

  • (Boolean)


81
82
83
# File 'lib/protocol/http/body/buffered.rb', line 81

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

#finishObject



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

def finish
  self
end

#inspectObject



102
103
104
# File 'lib/protocol/http/body/buffered.rb', line 102

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

#lengthObject



77
78
79
# File 'lib/protocol/http/body/buffered.rb', line 77

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

#readObject



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

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

#rewindObject



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

def rewind
  @index = 0
end

#write(chunk) ⇒ Object



93
94
95
96
# File 'lib/protocol/http/body/buffered.rb', line 93

def write(chunk)
  @digest&.update(chunk)
  @chunks << chunk
end