Sha256: 3b2c4abd6ffddd3f80ff83db369f66706aff0cc34fd3513d6475381fdf16e91b

Contents?: true

Size: 922 Bytes

Versions: 1

Compression:

Stored size: 922 Bytes

Contents

module Cognition
  class Matcher
    attr_reader :trigger, :action, :response, :help, :match_data

    def initialize(trigger, options = {}, &action)
      fail ArgumentError, "matcher must have a trigger" unless trigger
      fail ArgumentError, "matcher must have a action" unless action
      @trigger = trigger
      @help = options[:help] ||= {}
      @action = action
    end

    def help
      @help.map do |command, description|
        "#{command} - #{description}"
      end
    end

    def attempt(msg)
      return false unless matches?(msg)

      run(msg)
    end

    def run(msg)
      @response = action.call(msg, match_data)
    rescue => e
      @response = "'#{msg.command}' found, but raised #{e.inspect}"
    end

    def matches?(msg)
      case trigger
      when String
        trigger == msg.command
      when Regexp
        @match_data = trigger.match msg.command
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
cognition-2.0.5 lib/cognition/matcher.rb