Class: Akasha::CommandRouter
- Inherits:
-
Object
- Object
- Akasha::CommandRouter
- Defined in:
- lib/akasha/command_router.rb,
lib/akasha/command_router/default_handler.rb
Overview
Routes commands to their handlers.
Defined Under Namespace
Classes: DefaultHandler
Constant Summary collapse
- NotFoundError =
Raised when no corresponding target can be found for a command.
Class.new(RuntimeError)
Instance Method Summary collapse
-
#initialize ⇒ CommandRouter
constructor
A new instance of CommandRouter.
-
#register_default_route(command, aggregate_class) ⇒ Object
Registers a default route, mapping a command to an aggregate class.
-
#register_route(command, lambda = nil, &block) ⇒ Object
Registers a custom route, specifying either a lambda or a block.
-
#route!(command, aggregate_id, **data) ⇒ Object
Routes a command to the registered target.
Constructor Details
#initialize ⇒ CommandRouter
Returns a new instance of CommandRouter.
9 10 11 |
# File 'lib/akasha/command_router.rb', line 9 def initialize @routes = {} end |
Instance Method Details
#register_default_route(command, aggregate_class) ⇒ Object
Registers a default route, mapping a command to an aggregate class. As a result, when ‘#route!` is called for that command, the aggregate will be loaded from repository, the command will be sent to the object to invoke the object’s method, and finally the aggregate will be saved.
24 25 26 |
# File 'lib/akasha/command_router.rb', line 24 def register_default_route(command, aggregate_class) register_route(command, DefaultHandler.new(aggregate_class)) end |
#register_route(command, lambda = nil, &block) ⇒ Object
Registers a custom route, specifying either a lambda or a block. If both lambda and block are specified, lambda takes precedence.
15 16 17 18 |
# File 'lib/akasha/command_router.rb', line 15 def register_route(command, lambda = nil, &block) callable = lambda || block @routes[command] = callable end |
#route!(command, aggregate_id, **data) ⇒ Object
Routes a command to the registered target. Raises NotFoundError if no corresponding target can be found.
30 31 32 33 34 |
# File 'lib/akasha/command_router.rb', line 30 def route!(command, aggregate_id, **data) handler = @routes[command] return handler.call(command, aggregate_id, **data) if handler raise NotFoundError, "Target for command #{command.inspect} not found" end |