Class: Octiron::Events::Bus
- Inherits:
-
Object
- Object
- Octiron::Events::Bus
- Includes:
- Support::Identifiers
- Defined in:
- lib/octiron/events/bus.rb
Overview
Implements and in-process pub-sub events broadcaster allowing multiple observers to subscribe to different events.
Constant Summary collapse
- DEFAULT_CLASS =
The default handler class
'octiron-default'.freeze
Instance Attribute Summary collapse
-
#default_namespace ⇒ String
readonly
The default namespace to search for events.
Instance Method Summary collapse
-
#clear ⇒ Object
Clears all event handlers.
-
#initialize(default_namespace = ::Octiron::Events) ⇒ Bus
constructor
A new instance of Bus.
-
#publish(event) ⇒ Object
(also: #broadcast, #notify)
Broadcast an event.
-
#subscribe(event_id, handler_object = nil, handler_class = DEFAULT_CLASS, &handler_proc) ⇒ Object
(also: #register)
Subscribe an event handler to an event.
-
#unsubscribe(event_id, handler_object = nil, handler_class = DEFAULT_CLASS, &handler_proc) ⇒ Object
Unsubscribe an event handler from an event.
Methods included from Support::Identifiers
Methods included from Support::Constantize
Methods included from Support::CamelCase
Constructor Details
Instance Attribute Details
#default_namespace ⇒ String (readonly)
Returns the default namespace to search for events.
22 23 24 |
# File 'lib/octiron/events/bus.rb', line 22 def default_namespace @default_namespace end |
Instance Method Details
#clear ⇒ Object
Clears all event handlers
37 38 39 |
# File 'lib/octiron/events/bus.rb', line 37 def clear @handlers = {} end |
#publish(event) ⇒ Object Also known as: broadcast, notify
Broadcast an event. This is an instance of a class provided to #subscribe previously.
90 91 92 93 94 95 96 97 98 99 100 |
# File 'lib/octiron/events/bus.rb', line 90 def publish(event) event_name = event if not event.is_a?(Hash) event_name = event.class.to_s end @handlers.keys.sort.each do |handler_class| handlers_for(event_name, handler_class, false).each do |handler| handler.call(event) end end end |
#subscribe(event_id, handler_object = nil, handler_class = DEFAULT_CLASS, &handler_proc) ⇒ Object Also known as: register
Subscribe an event handler to an event.
55 56 57 58 59 60 61 |
# File 'lib/octiron/events/bus.rb', line 55 def subscribe(event_id, handler_object = nil, handler_class = DEFAULT_CLASS, &handler_proc) return with_handlers(event_id, handler_class, handler_object, handler_proc) do |hlist, h| hlist << h end end |
#unsubscribe(event_id, handler_object = nil, handler_class = DEFAULT_CLASS, &handler_proc) ⇒ Object
Unsubscribe an event handler from an event.
78 79 80 81 82 83 84 |
# File 'lib/octiron/events/bus.rb', line 78 def unsubscribe(event_id, handler_object = nil, handler_class = DEFAULT_CLASS, &handler_proc) return with_handlers(event_id, handler_class, handler_object, handler_proc) do |hlist, h| hlist.delete(h) end end |