Class: Vedeu::API::Events

Inherits:
Object
  • Object
show all
Defined in:
lib/vedeu/api/events.rb

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Events

Returns a new instance of Events.



4
5
6
7
8
9
10
11
12
13
# File 'lib/vedeu/api/events.rb', line 4

def initialize(&block)
  @handlers = Hash.new do |hash, key|
    hash[key] = {
      delay:     0,
      events:    [],
      last_exec: 0,
    }
  end
  instance_eval(&block) if block_given?
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object (private)



41
42
43
# File 'lib/vedeu/api/events.rb', line 41

def method_missing(method, *args, &block)
  @self_before_instance_eval.send method, *args, &block
end

Instance Method Details

#add(object, &block) ⇒ Object



15
16
17
18
19
# File 'lib/vedeu/api/events.rb', line 15

def add(object, &block)
  @self_before_instance_eval = eval('self', block.binding)

  instance_eval(&block)
end

#event(event, delay = 0, &block) ⇒ Object



21
22
23
24
25
# File 'lib/vedeu/api/events.rb', line 21

def event(event, delay = 0, &block)
  handlers[event][:events] << block
  handlers[event][:delay]  = delay
  handlers[event]
end

#trigger(event, *args) ⇒ Object



27
28
29
30
31
32
33
34
35
# File 'lib/vedeu/api/events.rb', line 27

def trigger(event, *args)
  elapsed = Time.now.to_f - handlers[event][:last_exec]

  if elapsed > handlers[event][:delay]
    handlers[event][:last_exec] = Time.now.to_f

    handlers[event][:events].each { |handler| handler.call(*args) }
  end
end