Class: Sequent::Core::Helpers::MessageRouter

Inherits:
Object
  • Object
show all
Defined in:
lib/sequent/core/helpers/message_router.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeMessageRouter

Returns a new instance of MessageRouter.



12
13
14
# File 'lib/sequent/core/helpers/message_router.rb', line 12

def initialize
  clear_routes
end

Instance Attribute Details

#instanceof_routesObject (readonly)

Returns the value of attribute instanceof_routes.



10
11
12
# File 'lib/sequent/core/helpers/message_router.rb', line 10

def instanceof_routes
  @instanceof_routes
end

#routesObject (readonly)

Returns the value of attribute routes.



10
11
12
# File 'lib/sequent/core/helpers/message_router.rb', line 10

def routes
  @routes
end

Instance Method Details

#clear_routesObject

Removes all routes from the router.



57
58
59
60
# File 'lib/sequent/core/helpers/message_router.rb', line 57

def clear_routes
  @instanceof_routes = {}
  @routes = {}
end

#match_message(message) ⇒ Object

Returns a set of handlers that match the given message, or an empty set when none match.



37
38
39
40
41
42
43
44
# File 'lib/sequent/core/helpers/message_router.rb', line 37

def match_message(message)
  result = Set.new
  result.merge(@instanceof_routes[message.class]) if @instanceof_routes.include?(message.class)
  @routes.each do |matcher, handlers|
    result.merge(handlers) if matcher.matches_message?(message)
  end
  result
end

#matches_message?(message) ⇒ Boolean

Returns true when there is at least one handler for the given message, or false otherwise.

Returns:



49
50
51
52
# File 'lib/sequent/core/helpers/message_router.rb', line 49

def matches_message?(message)
  @instanceof_routes.include?(message.class) ||
    @routes.keys.any? { |matcher| matcher.matches_message?(message) }
end

#register_matchers(*matchers, handler) ⇒ Object

Registers a handler for the given matchers.

A matcher must implement #matches_message?(message) and return a truthy value when it matches, or a falsey value otherwise.



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/sequent/core/helpers/message_router.rb', line 22

def register_matchers(*matchers, handler)
  fail ArgumentError, 'handler is required' if handler.nil?

  matchers.each do |matcher|
    if matcher.is_a?(MessageMatchers::InstanceOf)
      (@instanceof_routes[matcher.expected_class] ||= Set.new) << handler
    else
      (@routes[matcher] ||= Set.new) << handler
    end
  end
end