Class: Callback::CallbackContainer

Inherits:
Object
  • Object
show all
Defined in:
lib/spec/callback/callback_container.rb

Instance Method Summary collapse

Constructor Details

#initializeCallbackContainer

Returns a new instance of CallbackContainer.



3
4
5
6
7
# File 'lib/spec/callback/callback_container.rb', line 3

def initialize
  @callback_registry = Hash.new do |hash, key|
    hash[key] = Array.new
  end
end

Instance Method Details

#clearObject

Clears all of the callbacks in this container.



42
43
44
# File 'lib/spec/callback/callback_container.rb', line 42

def clear
  @callback_registry.clear
end

#define(key, callback_proc = nil, &callback_block) ⇒ Object

Defines the callback with the key in this container.



10
11
12
13
14
15
16
# File 'lib/spec/callback/callback_container.rb', line 10

def define(key, callback_proc=nil, &callback_block)
  callback = extract_callback(callback_block, callback_proc) do
    raise "You must define the callback that accepts the call method."
  end
  @callback_registry[key] << callback
  callback
end

#notify(key, *args, &error_handler) ⇒ Object

Notifies the callbacks for the key. Arguments may be passed. An error handler may be passed in as a block. If there is an error, the block is called with error object as an argument. An array of the return values of the callbacks is returned.



31
32
33
34
35
36
37
38
39
# File 'lib/spec/callback/callback_container.rb', line 31

def notify(key, *args, &error_handler)
  @callback_registry[key].collect do |callback|
    begin
      callback.call(*args)
    rescue Exception => e
      yield(e) if error_handler
    end
  end
end

#undefine(key, callback_proc) ⇒ Object

Undefines the callback with the key in this container.



19
20
21
22
23
24
25
# File 'lib/spec/callback/callback_container.rb', line 19

def undefine(key, callback_proc)
  callback = extract_callback(callback_proc) do
    raise "You may only undefine callbacks that use the call method."
  end
  @callback_registry[key].delete callback
  callback
end