Module: RubyPi::Agent::EventEmitter
- Included in:
- Core
- Defined in:
- lib/ruby_pi/agent/events.rb
Overview
Mixin that adds event subscription and emission to any class. Include this module and call ‘on`, `emit`, and `off` to wire up event-driven communication between components.
Instance Method Summary collapse
-
#emit(event, data = {}) ⇒ void
Fires all handlers registered for the given event type.
-
#off(event, &block) ⇒ Proc?
Removes a specific handler from an event’s subscriber list.
-
#on(event, &block) ⇒ Proc
Subscribes a handler block to a specific event type.
Instance Method Details
#emit(event, data = {}) ⇒ void
This method returns an undefined value.
Fires all handlers registered for the given event type. Each handler receives the ‘data` hash as its argument. Handlers that raise are rescued individually — one failing handler does not prevent others from executing.
71 72 73 74 75 76 77 78 79 80 81 82 83 |
# File 'lib/ruby_pi/agent/events.rb', line 71 def emit(event, data = {}) validate_event!(event) event_handlers[event].each do |handler| handler.call(data) rescue StandardError => e # Log but do not propagate handler errors — they should not break # the agent loop. Emit an :error event if this is not already an # error event (to prevent infinite recursion). if event != :error emit(:error, error: e, source: :event_handler, event: event) end end end |
#off(event, &block) ⇒ Proc?
Removes a specific handler from an event’s subscriber list. If the handler is not found, this is a no-op. Pass the same block reference that was given to ‘on`.
92 93 94 95 |
# File 'lib/ruby_pi/agent/events.rb', line 92 def off(event, &block) validate_event!(event) event_handlers[event].delete(block) end |
#on(event, &block) ⇒ Proc
Subscribes a handler block to a specific event type. The block will be called every time ‘emit` fires for that event. Multiple handlers can be registered for the same event — they are invoked in the order they were registered.
57 58 59 60 61 |
# File 'lib/ruby_pi/agent/events.rb', line 57 def on(event, &block) validate_event!(event) event_handlers[event] << block block end |