Class: Protocol::HTTP::Body::Completable

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

Overview

Invokes a callback once the body has completed, either successfully or due to an error.

Instance Attribute Summary

Attributes inherited from Wrapper

#body

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Wrapper

#The wrapped body.=, #buffered, #discard, #empty?, #length, #read, #ready?, #to_json

Methods inherited from Readable

#buffered, #call, #discard, #each, #empty?, #finish, #join, #length, #read, #ready?, #stream?, #to_json

Constructor Details

#initialize(body, callback) ⇒ Completable

Initialize the completable body with a callback.



29
30
31
32
33
# File 'lib/protocol/http/body/completable.rb', line 29

def initialize(body, callback)
	super(body)
	
	@callback = callback
end

Class Method Details

.wrap(message, &block) ⇒ Object

Wrap a message body with a callback. If the body is empty, the callback is invoked immediately.



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

def self.wrap(message, &block)
	if body = message&.body and !body.empty?
		message.body = self.new(message.body, block)
	else
		yield
	end
end

Instance Method Details

#as_jsonObject

Convert the body to a hash suitable for serialization.



60
61
62
63
64
# File 'lib/protocol/http/body/completable.rb', line 60

def as_json(...)
	super.merge(
		callback: @callback&.to_s
	)
end

#close(error = nil) ⇒ Object

Close the body and invoke the callback. If an error is given, it is passed to the callback.

The calback is only invoked once, and before ‘super` is invoked.



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

def close(error = nil)
	if @callback
		@callback.call(error)
		@callback = nil
	end
	
	super
end

#inspectObject

Inspect the completable body.



69
70
71
72
# File 'lib/protocol/http/body/completable.rb', line 69

def inspect
	callback_status = @callback ? "callback pending" : "callback completed"
	return "#{super} | #<#{self.class} #{callback_status}>"
end

#rewindObject

Rewind the body, is not supported.



41
42
43
# File 'lib/protocol/http/body/completable.rb', line 41

def rewind
	false
end

#rewindable?Boolean

Returns:

  • (Boolean)


36
37
38
# File 'lib/protocol/http/body/completable.rb', line 36

def rewindable?
	false
end