class WeChat::Bot::Handler

Handler

Attributes

args[R]

@return [Array]

block[R]

@return [Proc]

bot[R]

@return [Core]

event[R]

@return [Symbol]

group[R]

@return [Symbol]

pattern[R]

@return [String]

thread_group[R]

@return [ThreadGroup] @api private

Public Class Methods

new(bot, event, pattern, options = {}, &block) click to toggle source
# File lib/wechat/bot/handler.rb, line 26
def initialize(bot, event, pattern, options = {}, &block)
  options              = {
    :group => nil,
    :execute_in_callback => false,
    :strip_colors => false,
    :args => []
  }.merge(options)

  @bot = bot
  @event = event
  @pattern = pattern
  @block = block
  @group = options[:group]
  @execute_in_callback = options[:execute_in_callback]
  @args = options[:args]

  @thread_group = ThreadGroup.new
end

Public Instance Methods

call(message, captures, arguments) click to toggle source

执行 Handler

@param [Symbol] message @param [String] captures @param [Array] arguments @return [Thread]

# File lib/wechat/bot/handler.rb, line 51
def call(message, captures, arguments)
  bargs = captures + arguments

  thread = Thread.new {
    @bot.logger.debug "[New thread] For #{self}: #{Thread.current} -- #{@thread_group.list.size} in total."
    begin
      if @execute_in_callback
        @bot.callback.instance_exec(message, *@args, *bargs, &@block)
      else
        @block.call(message, *@args, *bargs)
      end
    rescue => e
      @bot.logger.error "[Thread error] #{e.message} -> #{e.backtrace.join("\n")}"
    ensure
      @bot.logger.debug "[Thread done] For #{self}: #{Thread.current} -- #{@thread_group.list.size - 1} remaining."
    end
  }

  @thread_group.add(thread)
  thread
end
stop() click to toggle source

@return [void]

# File lib/wechat/bot/handler.rb, line 74
def stop
  @bot.logger.debug "[Stopping handler] Stopping all threads of handler #{self}: #{@thread_group.list.size} threads..."
  @thread_group.list.each do |thread|
    Thread.new do
      @bot.logger.debug "[Ending thread] Waiting 10 seconds for #{thread} to finish..."
      thread.join(10)
      @bot.logger.debug "[Killing thread] Killing #{thread}"
      thread.kill
    end
  end
end
to_s() click to toggle source

@return [String]

# File lib/wechat/bot/handler.rb, line 87
def to_s
  # TODO maybe add the number of running threads to the output?
  "#<Cinch::Handler @event=#{@event.inspect} pattern=#{@pattern.inspect}>"
end