Class: Akasha::EventRouterBase
- Inherits:
-
Object
- Object
- Akasha::EventRouterBase
- Defined in:
- lib/akasha/event_router_base.rb
Overview
Base class for routing events to event listeners.
Direct Known Subclasses
Instance Method Summary collapse
-
#initialize(routes = {}) ⇒ EventRouterBase
constructor
A new instance of EventRouterBase.
-
#register_event_listener(event_name, listener) ⇒ Object
Registers a new event listener, derived from ‘Akasha::EventListener`.
-
#route(event_name, aggregate_id, **data) ⇒ Object
Routes an event.
Constructor Details
#initialize(routes = {}) ⇒ EventRouterBase
Returns a new instance of EventRouterBase.
4 5 6 7 8 9 |
# File 'lib/akasha/event_router_base.rb', line 4 def initialize(routes = {}) @routes = Hash.new { |hash, key| hash[key] = [] } # Support both array of listeners and a single listener normalized_routes = routes.map { |command, listeners| [command, Array(listeners)] }.to_h @routes.merge!(normalized_routes) end |
Instance Method Details
#register_event_listener(event_name, listener) ⇒ Object
Registers a new event listener, derived from ‘Akasha::EventListener`.
13 14 15 |
# File 'lib/akasha/event_router_base.rb', line 13 def register_event_listener(event_name, listener) @routes[event_name] << listener end |
#route(event_name, aggregate_id, **data) ⇒ Object
Routes an event.
18 19 20 21 22 23 24 25 26 27 |
# File 'lib/akasha/event_router_base.rb', line 18 def route(event_name, aggregate_id, **data) @routes[event_name].each do |listener| listener = listener.new if listener.is_a?(Class) begin listener.public_send(:"on_#{event_name}", aggregate_id, **data) rescue RuntimeError => e log "Error handling event #{event_name.inspect}: #{e}" end end end |