Class: Akasha::CommandRouter

Inherits:
Object
  • Object
show all
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

Constructor Details

#initialize(routes = {}) ⇒ CommandRouter

Returns a new instance of CommandRouter


12
13
14
15
16
17
18
19
20
# File 'lib/akasha/command_router.rb', line 12

def initialize(routes = {})
  @routes = routes.flat_map do |command, target|
    if target.is_a?(Class)
      { command => DefaultHandler.new(target) }
    else
      { command => target }
    end
  end
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.


33
34
35
# File 'lib/akasha/command_router.rb', line 33

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.


24
25
26
27
# File 'lib/akasha/command_router.rb', line 24

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.

Raises:


39
40
41
42
43
# File 'lib/akasha/command_router.rb', line 39

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