Class: Ego::Handler

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/ego/handler.rb

Overview

Note:

Handlers should be registered by plug-ins using the Robot#on method.

Handlers map user queries to actions.

Examples:

Add a handler to the robot instance

robot.on(/^pattern/) do
  # ...
end

Add a handler with priority to the robot instance

robot.on(/^pattern/, 7) do
  # ...
end

Add multiple handlers for the same action

robot.on(
  /pattern/ => 6,
  /other pattern/ => 7,
  /another/ => 3,
) do
  # ...
end

Passing a lambda as a condition

robot.on(->(query) { query.length > 10 }) do
  # ...
end

See Also:

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(condition, action, priority = 5) ⇒ Handler

Returns a new instance of Handler.

Parameters:

  • condition (Proc, #match)

    the condition that triggers the supplied action

  • action (Proc)

    the block to be executed when condition is met

  • priority (Integer) (defaults to: 5)

    the handler priority (higher number = higher priority)



44
45
46
47
48
# File 'lib/ego/handler.rb', line 44

def initialize(condition, action, priority = 5)
  @condition = normalize(condition)
  @action = action
  @priority = priority
end

Instance Attribute Details

#actionObject (readonly)

Returns the value of attribute action.



39
40
41
# File 'lib/ego/handler.rb', line 39

def action
  @action
end

#conditionObject (readonly)

Returns the value of attribute condition.



39
40
41
# File 'lib/ego/handler.rb', line 39

def condition
  @condition
end

#priorityObject (readonly)

Returns the value of attribute priority.



39
40
41
# File 'lib/ego/handler.rb', line 39

def priority
  @priority
end

Instance Method Details

#<=>(other) ⇒ Object

Compare priority with other.priority.

Parameters:

  • other (Handler)

    the handler to compare with



53
54
55
# File 'lib/ego/handler.rb', line 53

def <=>(other)
  @priority <=> other.priority
end

#handle(query) ⇒ false, Array

Match the given query against the condition.

Parameters:

  • query (String)

    the query to match the condition against

Returns:

  • (false)

    if condition doesn't match

  • (Array)

    parameters to pass to the action



62
63
64
65
66
67
68
69
70
71
72
# File 'lib/ego/handler.rb', line 62

def handle(query)
  return false unless (result = @condition.call(query))

  @action.parameters.each_with_object([]) do |param, arr|
    begin
      arr << result[param.pop]
    rescue IndexError
      arr << nil # Match group isn't defined.
    end
  end
end