Class: WeChat::Bot::HandlerList

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/wechat/bot/handler_list.rb

Overview

Handler 列表

Instance Method Summary collapse

Constructor Details

#initializeHandlerList

Returns a new instance of HandlerList.



6
7
8
9
# File 'lib/wechat/bot/handler_list.rb', line 6

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

Instance Method Details

#dispatch(event, message = nil, *args) ⇒ Array<Thread>

分派执行 Handler

Parameters:

  • event (Symbol)
  • message (String) (defaults to: nil)
  • args (Array<Object>)

Returns:

  • (Array<Thread>)


40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/wechat/bot/handler_list.rb', line 40

def dispatch(event, message = nil, *args)
  threads = []

  if handlers = find(event, message)
    already_run = Set.new
    handlers.each do |handler|
      next if already_run.include?(handler.block)
      already_run.add(handler.block)

      if message
        captures = message.match(handler.pattern.to_r(message), event).captures
      else
        captures = []
      end

      threads.push(handler.call(message, captures, args))
    end
  end

  threads
end

#each(&block) ⇒ Object



81
82
83
# File 'lib/wechat/bot/handler_list.rb', line 81

def each(&block)
  @handlers.values.flatten.each(&block)
end

#find(type, message = nil) ⇒ Hander

查找匹配 Handler

Parameters:

  • type (Symbol)
  • message (String) (defaults to: nil)

Returns:

  • (Hander)


67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/wechat/bot/handler_list.rb', line 67

def find(type, message = nil)
  if handlers = @handlers[type]
    if message.nil?
      return handlers
    end

    handlers = handlers.select { |handler|
      message.match(handler.pattern.to_r(message), type)
    }.group_by {|handler| handler.group}

    handlers.values_at(*(handlers.keys - [nil])).map(&:first) + (handlers[nil] || [])
  end
end

#register(handler) ⇒ void

This method returns an undefined value.

注册 Handler

Parameters:



15
16
17
18
19
20
# File 'lib/wechat/bot/handler_list.rb', line 15

def register(handler)
  @mutex.synchronize do
    handler.bot.logger.debug "[on handler] Registering handler with pattern `#{handler.pattern}`, reacting on `#{handler.event}`"
    @handlers[handler.event].push(handler)
  end
end

#stop_allvoid

This method returns an undefined value.

停止运行所有 Handler



88
89
90
# File 'lib/wechat/bot/handler_list.rb', line 88

def stop_all
  each { |h| h.stop }
end

#unregister(*handlers) ⇒ void

This method returns an undefined value.

取消注册 Handler

Parameters:



26
27
28
29
30
31
32
# File 'lib/wechat/bot/handler_list.rb', line 26

def unregister(*handlers)
  @mutex.synchronize do
    handlers.each do |handler|
      @handlers[handler.event].delete(handler)
    end
  end
end