Class: WeChat::Bot::HandlerList
- Inherits:
-
Object
- Object
- WeChat::Bot::HandlerList
- Includes:
- Enumerable
- Defined in:
- lib/wechat/bot/handler_list.rb
Overview
Handler 列表
Instance Method Summary collapse
-
#dispatch(event, message = nil, *args) ⇒ Array<Thread>
分派执行 Handler.
- #each(&block) ⇒ Object
-
#find(type, message = nil) ⇒ Hander
查找匹配 Handler.
-
#initialize ⇒ HandlerList
constructor
A new instance of HandlerList.
-
#register(handler) ⇒ void
注册 Handler.
-
#stop_all ⇒ void
停止运行所有 Handler.
-
#unregister(*handlers) ⇒ void
取消注册 Handler.
Constructor Details
#initialize ⇒ HandlerList
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
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, = nil, *args) threads = [] if handlers = find(event, ) already_run = Set.new handlers.each do |handler| next if already_run.include?(handler.block) already_run.add(handler.block) if captures = .match(handler.pattern.to_r(), event).captures else captures = [] end threads.push(handler.call(, 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
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, = nil) if handlers = @handlers[type] if .nil? return handlers end handlers = handlers.select { |handler| .match(handler.pattern.to_r(), 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
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_all ⇒ void
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
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 |