Class: Ruwi::Dispatcher

Inherits:
Object
  • Object
show all
Defined in:
lib/ruwi/runtime/dispatcher.rb

Instance Method Summary collapse

Constructor Details

#initializeDispatcher

Returns a new instance of Dispatcher.



3
4
5
6
# File 'lib/ruwi/runtime/dispatcher.rb', line 3

def initialize
  @subs = {}
  @after_handlers = []
end

Instance Method Details

#after_every_command(handler) ⇒ Object

Parameters:

  • handler (Proc)


24
25
26
27
28
29
30
31
# File 'lib/ruwi/runtime/dispatcher.rb', line 24

def after_every_command(handler)
  @after_handlers << handler

  -> {
    idx = @after_handlers.index(handler)
    @after_handlers.delete_at(idx) if idx
  }
end

#dispatch(command_name, payload) ⇒ Object

Parameters:

  • command_name (String)
  • payload (Object)


35
36
37
38
39
40
41
42
43
44
# File 'lib/ruwi/runtime/dispatcher.rb', line 35

def dispatch(command_name, payload)
  command_name_sym = command_name.to_sym
  if @subs.key?(command_name_sym)
    @subs[command_name_sym].each { |handler| handler.call(payload) }
  else
    warn "No handlers for command: #{command_name}"
  end

  @after_handlers.each(&:call)
end

#subscribe(command_name, handler) ⇒ Object

Parameters:

  • command_name (String)


9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/ruwi/runtime/dispatcher.rb', line 9

def subscribe(command_name, handler)
  @subs[command_name] ||= []
  handlers = @subs[command_name]

  return -> {} if handlers.include?(handler)

  handlers << handler

  -> {
    idx = handlers.index(handler)
    handlers.delete_at(idx) if idx
  }
end