Class: Flexo::Trigger

Inherits:
Object
  • Object
show all
Defined in:
lib/flexo/trigger.rb

Overview

A Trigger is a special type of handler, designed to trigger an action when a certain Flexo::Events::PrivmsgEvent is receieved. The PrivmsgEvent is matched against a regexp, and, if it matches, the action is triggered.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(pattern, &block) ⇒ Trigger

Creates a trigger.

pattern is a string or a regular expression to match against the message. Any group matches will be passed as arguments to the block



15
16
17
18
19
20
21
# File 'lib/flexo/trigger.rb', line 15

def initialize(pattern, &block)
  @manager = Flexo::Manager.instance
  @pattern = Regexp.new(pattern)
  @prefix  = @manager.config['core.trigger_prefix']
  @block   = block
  @handler = @manager.dispatcher.subscribe(Flexo::Events::PrivmsgEvent, &self)
end

Instance Attribute Details

#patternObject (readonly)

Returns the value of attribute pattern.



7
8
9
# File 'lib/flexo/trigger.rb', line 7

def pattern
  @pattern
end

#prefixObject (readonly)

Returns the value of attribute prefix.



8
9
10
# File 'lib/flexo/trigger.rb', line 8

def prefix
  @prefix
end

Instance Method Details

#call(privmsg) ⇒ Object

Invokes the trigger



24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/flexo/trigger.rb', line 24

def call(privmsg)
  if(privmsg.text[0...@prefix.size] == @prefix)
    text = privmsg.text[@prefix.size..-1]
  elsif(privmsg.to_me? && privmsg.text[0...@prefix.length] == @prefix)
    text = privmsg.text[@prefix.size..-1]
  elsif(privmsg.to_me?)
    text = privmsg.text
  else
    return
  end

  m = text.match(@pattern)
  @block.call(privmsg, *m[1..-1]) if m
end

#to_procObject

Turns the Trigger into a Proc



40
41
42
# File 'lib/flexo/trigger.rb', line 40

def to_proc
  proc { |event| call(event) }
end

#unsubscribeObject



44
45
46
# File 'lib/flexo/trigger.rb', line 44

def unsubscribe
  @manager.dispatcher.unsubscribe @handler
end