Class: Protocol::HTTP::Body::Digestable

Inherits:
Wrapper show all
Defined in:
lib/protocol/http/body/digestable.rb

Overview

Invokes a callback once the body has finished reading.

Instance Attribute Summary collapse

Attributes inherited from Wrapper

#body

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Wrapper

#The wrapped body.=, #as_json, #buffered, #close, #discard, #empty?, #inspect, #length, #ready?, #rewind, #rewindable?, #to_json

Methods inherited from Readable

#as_json, #buffered, #call, #close, #discard, #each, #empty?, #finish, #join, #length, #ready?, #rewind, #rewindable?, #stream?, #to_json

Constructor Details

#initialize(body, digest = Digest::SHA256.new, callback = nil) ⇒ Digestable

Initialize the digestable body with a callback.



31
32
33
34
35
36
# File 'lib/protocol/http/body/digestable.rb', line 31

def initialize(body, digest = Digest::SHA256.new, callback = nil)
	super(body)
	
	@digest = digest
	@callback = callback
end

Instance Attribute Details

#digestObject (readonly)

Returns the value of attribute digest.



39
40
41
# File 'lib/protocol/http/body/digestable.rb', line 39

def digest
  @digest
end

Class Method Details

.wrap(message, digest = Digest::SHA256.new, &block) ⇒ Object

Wrap a message body with a callback. If the body is empty, the callback is not invoked, as there is no data to digest.



20
21
22
23
24
# File 'lib/protocol/http/body/digestable.rb', line 20

def self.wrap(message, digest = Digest::SHA256.new, &block)
	if body = message&.body and !body.empty?
		message.body = self.new(message.body, digest, block)
	end
end

Instance Method Details

#digest the digest object.=(thedigestobject. = (value)) ⇒ Object



39
# File 'lib/protocol/http/body/digestable.rb', line 39

attr :digest

#etag(weak: false) ⇒ Object

Generate an appropriate ETag for the digest, assuming it is complete. If you call this method before the body is fully read, the ETag will be incorrect.



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

def etag(weak: false)
	if weak
		"W/\"#{digest.hexdigest}\""
	else
		"\"#{digest.hexdigest}\""
	end
end

#readObject

Read the body and update the digest. When the body is fully read, the callback is invoked with ‘self` as the argument.



56
57
58
59
60
61
62
63
64
65
66
# File 'lib/protocol/http/body/digestable.rb', line 56

def read
	if chunk = super
		@digest.update(chunk)
		
		return chunk
	else
		@callback&.call(self)
		
		return nil
	end
end