Class: Ego::Handler

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

Constant Summary collapse

@@handlers =
{}
@@listeners =
[]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ Handler

Returns a new instance of Handler.



12
13
14
# File 'lib/ego/handler.rb', line 12

def initialize name
  @name = name
end

Instance Attribute Details

#descriptionObject

Returns the value of attribute description.



10
11
12
# File 'lib/ego/handler.rb', line 10

def description
  @description
end

#nameObject (readonly)

Returns the value of attribute name.



9
10
11
# File 'lib/ego/handler.rb', line 9

def name
  @name
end

Class Method Details

.dispatch(robot, query) ⇒ Object



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

def self.dispatch robot, query
  @@listeners.sort.reverse_each do |listener|
    if params = listener.match(query)
      return @@handlers[listener.handler].run(robot, params)
    end
  end
end

.handlersObject



72
73
74
# File 'lib/ego/handler.rb', line 72

def self.handlers
  @@handlers
end

.has(handler_name) ⇒ Object



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

def self.has handler_name
  @@handlers.has_key? handler_name
end

.load(handler_names) ⇒ Object



57
58
59
60
61
62
# File 'lib/ego/handler.rb', line 57

def self.load handler_names
  handler_names.each do |path|
    handler = File.basename(path, '.*')
    require path unless has(handler)
  end
end

.register(name: nil) {|handler| ... } ⇒ Object

Yields:

  • (handler)


41
42
43
44
45
46
47
48
49
50
51
# File 'lib/ego/handler.rb', line 41

def self.register name: nil
  if name.nil?
    handler_path = caller_locations(1, 1)[0].absolute_path
    name = File.basename(handler_path, '.*')
  end

  handler = Ego::Handler.new(name)
  yield handler

  @@handlers[handler.name] = handler
end

Instance Method Details

#listen(pattern, priority: 5, &parser) ⇒ Object



20
21
22
23
24
25
# File 'lib/ego/handler.rb', line 20

def listen pattern, priority: 5, &parser
  unless block_given?
    parser = Proc.new { |matches| matches }
  end
  @@listeners << Ego::Listener.new(pattern, priority, parser, @name)
end

#run(robot = nil, params = nil, &action) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/ego/handler.rb', line 27

def run robot = nil, params = nil, &action
  if block_given?
    @action = action
  end

  if robot.nil?
    return
  elsif @action.arity == 1
    @action.call(robot)
  else
    @action.call(robot, params)
  end
end

#to_sObject



16
17
18
# File 'lib/ego/handler.rb', line 16

def to_s
  "#{@description}"
end