Class: EventBus
- Inherits:
-
Object
- Object
- EventBus
- Defined in:
- lib/event_bus.rb,
lib/event_bus/registrations.rb
Defined Under Namespace
Classes: Registrations
Class Method Summary collapse
-
.clear ⇒ Object
Delete all current listener registrations.
-
.publish(event_name, payload = {}) ⇒ EventBus
(also: announce, broadcast)
Announce an event to any waiting listeners.
-
.subscribe(pattern, listener = nil, method_name = nil, &blk) ⇒ EventBus
(also: listen_for)
Subscribe to a set of events.
Class Method Details
.clear ⇒ Object
Delete all current listener registrations
76 77 78 79 |
# File 'lib/event_bus.rb', line 76 def clear registrations.clear self end |
.publish(event_name, payload = {}) ⇒ EventBus Also known as: announce, broadcast
Announce an event to any waiting listeners.
The event_name
is added to the payload
hash (with the key :event_name
) before being passed on to listeners.
17 18 19 20 21 22 23 24 25 |
# File 'lib/event_bus.rb', line 17 def publish(event_name, payload = {}) case event_name when Symbol, String registrations.announce(event_name, payload) self else raise ArgumentError.new('The event name must be a string or a symbol') end end |
.subscribe(pattern, listener = nil, method_name = nil, &blk) ⇒ EventBus Also known as: listen_for
Subscribe to a set of events.
If blk
is supplied, it will be called with any event whose name matches pattern
.
If no block is given, and if pattern
is a String or a Regexp, a method will be called on listener
whenever an event matching pattern
occurs. In this case, if method_name
is supplied the EventBus will look for, and call, a method of that name on listener
; otherwise if method_name
is not given, the EventBus will attempt to call a method whose name matches the event’s name.
Finally, if no block is given and pattern
is not a String or a Regexp, then pattern
is taken to be a listener object and the EventBus will attempt to call a method on it whose name matches the event’s name.
Either listener
or blk
must be provided, both never both.
When a matching event occurs, either the block is called or the method_name
method on the listener
object is called.
57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/event_bus.rb', line 57 def subscribe(pattern, listener = nil, method_name = nil, &blk) case pattern when Regexp, String, Symbol subscribe_pattern(pattern, listener, method_name, &blk) else raise ArgumentError.new('You cannot give two listeners') if listener || method_name raise ArgumentError.new('You cannot give both a listener and a block') if block_given? subscribe_obj(pattern) end self end |