Class: Cognition::Matcher

Inherits:
Object
  • Object
show all
Defined in:
lib/cognition/matcher.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(trigger, options = {}, &action) ⇒ Matcher

Returns a new instance of Matcher.



5
6
7
8
9
10
11
# File 'lib/cognition/matcher.rb', line 5

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

Instance Attribute Details

#actionObject (readonly)

Returns the value of attribute action.



3
4
5
# File 'lib/cognition/matcher.rb', line 3

def action
  @action
end

#helpObject (readonly)

Returns the value of attribute help.



3
4
5
# File 'lib/cognition/matcher.rb', line 3

def help
  @help
end

#match_dataObject (readonly)

Returns the value of attribute match_data.



3
4
5
# File 'lib/cognition/matcher.rb', line 3

def match_data
  @match_data
end

#responseObject (readonly)

Returns the value of attribute response.



3
4
5
# File 'lib/cognition/matcher.rb', line 3

def response
  @response
end

#triggerObject (readonly)

Returns the value of attribute trigger.



3
4
5
# File 'lib/cognition/matcher.rb', line 3

def trigger
  @trigger
end

Instance Method Details

#attempt(msg) ⇒ Object



19
20
21
22
# File 'lib/cognition/matcher.rb', line 19

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

#matches?(msg) ⇒ Boolean

Returns:

  • (Boolean)


30
31
32
33
34
35
36
37
# File 'lib/cognition/matcher.rb', line 30

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

#run(msg) ⇒ Object



24
25
26
27
28
# File 'lib/cognition/matcher.rb', line 24

def run(msg)
  @response = action.call(msg, match_data).to_s
rescue => e
  @response = "#{e.class}: #{e.message}\n#{e.backtrace.join("\n")}"
end