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.

Raises:

  • (ArgumentError)


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

def initialize(trigger, options = {}, &action)
  raise ArgumentError, 'matcher must have a trigger' unless trigger
  raise ArgumentError, 'matcher must have a 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
23
# File 'lib/cognition/matcher.rb', line 19

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

  run(msg)
end

#matches?(msg) ⇒ Boolean

Returns:

  • (Boolean)


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

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

#run(msg) ⇒ Object



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

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