Skip to content

Commit 8b66234

Browse files
Merge pull request #451 from zilverline/optimize-message-router
Optimize `MessageRouter#matches_message?`
2 parents 8fb196c + ae70d77 commit 8b66234

File tree

2 files changed

+15
-7
lines changed

2 files changed

+15
-7
lines changed

lib/sequent/core/helpers/message_router.rb

+9-6
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,13 @@ def initialize
2020
# or a falsey value otherwise.
2121
#
2222
def register_matchers(*matchers, handler)
23+
fail ArgumentError, 'handler is required' if handler.nil?
24+
2325
matchers.each do |matcher|
2426
if matcher.is_a?(MessageMatchers::InstanceOf)
25-
@instanceof_routes[matcher.expected_class] << handler
27+
(@instanceof_routes[matcher.expected_class] ||= Set.new) << handler
2628
else
27-
@routes[matcher] << handler
29+
(@routes[matcher] ||= Set.new) << handler
2830
end
2931
end
3032
end
@@ -34,7 +36,7 @@ def register_matchers(*matchers, handler)
3436
#
3537
def match_message(message)
3638
result = Set.new
37-
result.merge(@instanceof_routes[message.class])
39+
result.merge(@instanceof_routes[message.class]) if @instanceof_routes.include?(message.class)
3840
@routes.each do |matcher, handlers|
3941
result.merge(handlers) if matcher.matches_message?(message)
4042
end
@@ -45,15 +47,16 @@ def match_message(message)
4547
# Returns true when there is at least one handler for the given message, or false otherwise.
4648
#
4749
def matches_message?(message)
48-
match_message(message).any?
50+
@instanceof_routes.include?(message.class) ||
51+
@routes.keys.any? { |matcher| matcher.matches_message?(message) }
4952
end
5053

5154
##
5255
# Removes all routes from the router.
5356
#
5457
def clear_routes
55-
@instanceof_routes = Hash.new { |h, k| h[k] = Set.new }
56-
@routes = Hash.new { |h, k| h[k] = Set.new }
58+
@instanceof_routes = {}
59+
@routes = {}
5760
end
5861
end
5962
end

spec/lib/sequent/core/helpers/message_router_spec.rb

+6-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,12 @@
99
let(:other_handler) { double('other handler') }
1010

1111
describe '#match_message' do
12-
subject { message_router.match_message(message) }
12+
subject do
13+
handlers = message_router.match_message(message)
14+
# `match_message` must be consistent with `matches_message?`
15+
expect(handlers.present?).to eq(message_router.matches_message?(message))
16+
handlers
17+
end
1318

1419
class MyMessage < Sequent::Event; end
1520

0 commit comments

Comments
 (0)