Class: Async::Matrix::ApplicationService::Dispatcher

Inherits:
Object
  • Object
show all
Defined in:
lib/async/matrix/application_service/dispatcher.rb

Overview

Routes incoming Matrix events to registered handler objects.

Each handler declares the event types it handles via ‘#event_types`. When an event arrives, the dispatcher finds all matching handlers and calls them. Errors in one handler do not prevent others from running.

Instance Method Summary collapse

Constructor Details

#initializeDispatcher

Returns a new instance of Dispatcher.



19
20
21
# File 'lib/async/matrix/application_service/dispatcher.rb', line 19

def initialize
	@handlers = Hash.new { |h, k| h[k] = [] }
end

Instance Method Details

#dispatch(event) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/async/matrix/application_service/dispatcher.rb', line 30

def dispatch(event)
	type     = event.type
	handlers = @handlers[type]

	if handlers.empty?
		Console.debug(self) { "No handler for event type: #{type}" }
		return
	end

	handlers.each do |handler|
		handler.call(event)
	rescue => e
		Console.error(self) { "Handler #{handler.class.name} raised #{e.class}: #{e.message}" }
	end
end

#dispatch_transaction(body) ⇒ Object



46
47
48
49
50
# File 'lib/async/matrix/application_service/dispatcher.rb', line 46

def dispatch_transaction(body)
	txn = Transaction.new(body)
	txn.events.each    { |event| dispatch(event) }
	txn.ephemeral.each { |event| dispatch(event) }
end

#handler_countObject



52
53
54
# File 'lib/async/matrix/application_service/dispatcher.rb', line 52

def handler_count
	@handlers.values.flatten.size
end

#register(handler) ⇒ Object



23
24
25
26
27
28
# File 'lib/async/matrix/application_service/dispatcher.rb', line 23

def register(handler)
	handler.event_types.each do |type|
		@handlers[type] << handler
		Console.info(self) { "Registered #{handler.class.name} for #{type}" }
	end
end