Class: CallbacksAttachable::CallbackHandler
- Inherits:
-
Object
- Object
- CallbacksAttachable::CallbackHandler
- Defined in:
- lib/callbacks_attachable/callback_handler.rb
Instance Method Summary collapse
-
#initialize(object, callback_class) ⇒ CallbackHandler
constructor
A new instance of CallbackHandler.
- #off(event, callback) ⇒ Object
- #on(event, skip: 0, &callback) ⇒ Object
- #once_on(event, *opts, &callback) ⇒ Object
- #trigger(event, *args, **opts) ⇒ Object
- #until_true_on(event, *opts, &callback) ⇒ Object
Constructor Details
#initialize(object, callback_class) ⇒ CallbackHandler
Returns a new instance of CallbackHandler.
3 4 5 6 |
# File 'lib/callbacks_attachable/callback_handler.rb', line 3 def initialize(object, callback_class) @object = object @callback_class = callback_class end |
Instance Method Details
#off(event, callback) ⇒ Object
39 40 41 42 |
# File 'lib/callbacks_attachable/callback_handler.rb', line 39 def off(event, callback) return unless __callbacks__[event] __callbacks__[event].delete(callback) end |
#on(event, skip: 0, &callback) ⇒ Object
8 9 10 11 12 |
# File 'lib/callbacks_attachable/callback_handler.rb', line 8 def on(event, skip: 0, &callback) __callbacks__[event] ||= [] __callbacks__[event] << @callback_class.new(@object, skip: skip, &callback) __callbacks__[event].last end |
#once_on(event, *opts, &callback) ⇒ Object
14 15 16 17 18 19 20 |
# File 'lib/callbacks_attachable/callback_handler.rb', line 14 def once_on(event, *opts, &callback) callback_registry = self registered_callback = on(event, *opts) do |*args| callback_registry.off(event, registered_callback) yield(*args) end end |
#trigger(event, *args, **opts) ⇒ Object
31 32 33 34 35 36 37 |
# File 'lib/callbacks_attachable/callback_handler.rb', line 31 def trigger(event, *args, **opts) return true if __callbacks__[event].nil? # dup the callback list so that removing callbacks while iterating does # still call all callbacks during map. __callbacks__[event].dup.all?{ |callback| callback.call(*args, **opts) } end |
#until_true_on(event, *opts, &callback) ⇒ Object
22 23 24 25 26 27 28 29 |
# File 'lib/callbacks_attachable/callback_handler.rb', line 22 def until_true_on(event, *opts, &callback) callback_registry = self registered_callback = on(event, *opts) do |*args| yield(*args).tap do |result| callback_registry.off(event, registered_callback) if result end end end |