Module: Esse::Events::Publisher::ClassMethods
- Defined in:
- lib/esse/events/publisher.rb
Overview
Class interface for publishers
Instance Method Summary collapse
-
#__bus__ ⇒ Bus
private
Internal event bus.
-
#instrument(event_id, payload = {}, &block) ⇒ Object
Publish an event with extra runtime information to the payload.
-
#publish(event_id, payload = {}) ⇒ Object
Publish an event.
-
#register_event(event_id, payload = {}) ⇒ self
Register a new event type.
-
#subscribe(object_or_event_id, &block) ⇒ Object
Subscribe to events.
-
#subscribed?(listener) ⇒ Boolean
Return true if a given listener has been subscribed to any event.
-
#unsubscribe(listener) ⇒ self
Unsubscribe a listener.
Instance Method Details
#__bus__ ⇒ Bus
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Internal event bus
113 114 115 |
# File 'lib/esse/events/publisher.rb', line 113 def __bus__ @__bus__ ||= Bus.new end |
#instrument(event_id, payload = {}, &block) ⇒ Object
Publish an event with extra runtime information to the payload
53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/esse/events/publisher.rb', line 53 def instrument(event_id, payload = {}, &block) publish_event = false # ensure block is also called on error raise(UnregisteredEventError, event_id) unless __bus__.can_handle?(event_id) payload[:__started_at__] = Time.now block.call(payload).tap { publish_event = true } ensure if publish_event payload[:runtime] ||= Time.now - payload.delete(:__started_at__) if payload[:__started_at__] __bus__.publish(event_id, payload) end end |
#publish(event_id, payload = {}) ⇒ Object
Publish an event
37 38 39 40 41 42 43 44 |
# File 'lib/esse/events/publisher.rb', line 37 def publish(event_id, payload = {}) if __bus__.can_handle?(event_id) __bus__.publish(event_id, payload) self else raise UnregisteredEventError, event_id end end |
#register_event(event_id, payload = {}) ⇒ self
Register a new event type
25 26 27 28 |
# File 'lib/esse/events/publisher.rb', line 25 def register_event(event_id, payload = {}) __bus__.events[event_id] = Event.new(event_id, payload) self end |
#subscribe(object_or_event_id, &block) ⇒ Object
Subscribe to events.
76 77 78 79 80 81 82 83 84 85 86 87 88 |
# File 'lib/esse/events/publisher.rb', line 76 def subscribe(object_or_event_id, &block) if __bus__.can_handle?(object_or_event_id) if block __bus__.subscribe(object_or_event_id, &block) else __bus__.attach(object_or_event_id) end self else raise InvalidSubscriberError, object_or_event_id end end |
#subscribed?(listener) ⇒ Boolean
Return true if a given listener has been subscribed to any event
104 105 106 |
# File 'lib/esse/events/publisher.rb', line 104 def subscribed?(listener) __bus__.subscribed?(listener) end |
#unsubscribe(listener) ⇒ self
Unsubscribe a listener
97 98 99 |
# File 'lib/esse/events/publisher.rb', line 97 def unsubscribe(listener) __bus__.detach(listener) end |