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

#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.



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

def clear_routes
  @routes = Hash.new { |h, k| h[k] = Set.new }
end

#match_message(message) ⇒ Object

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



31
32
33
34
35
36
37
# File 'lib/sequent/core/helpers/message_router.rb', line 31

def match_message(message)
  @routes
    .reduce(Set.new) do |memo, (matcher, handlers)|
      memo = memo.merge(handlers) if matcher.matches_message?(message)
      memo
    end
end

#matches_message?(message) ⇒ Boolean

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

Returns:



42
43
44
# File 'lib/sequent/core/helpers/message_router.rb', line 42

def matches_message?(message)
  match_message(message).any?
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
# File 'lib/sequent/core/helpers/message_router.rb', line 22

def register_matchers(*matchers, handler)
  matchers.each do |matcher|
    @routes[matcher] << handler
  end
end