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



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/async/matrix/application_service/dispatcher.rb', line 37

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

  if handlers.empty?
    Console.debug(self) { "No handler for event type: #{type}" }
  else
    handlers.each do |handler|
      begin
        handler.call(event)
      rescue => e
        Console.error(self) { "Handler #{handler.class.name} raised #{e.class}: #{e.message}" }
      end
    end
  end
end

#dispatch_transaction(body) ⇒ Object



30
31
32
33
34
35
# File 'lib/async/matrix/application_service/dispatcher.rb', line 30

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

#handler_countObject



54
55
56
# File 'lib/async/matrix/application_service/dispatcher.rb', line 54

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