Class: Webgen::Blackboard

Inherits:
Object
  • Object
show all
Defined in:
lib/webgen/blackboard.rb

Overview

A blackboard object provides methods for inter-object communication. Objects may register themselves for specific messsage names and get notified when such a message gets dispatched.

For a list of all available messages have a look at the Webgen documentation page.

Instance Method Summary collapse

Constructor Details

#initializeBlackboard

Create a new Blackboard object.



12
13
14
# File 'lib/webgen/blackboard.rb', line 12

def initialize
  @listener = {}
end

Instance Method Details

#add_listener(msg_name, id = nil, position = {}, &block) ⇒ Object

Add the given block as listener for the message msg_name.

The id parameter can be used to specify a string which uniquely identifies the listener.

The position parameter can be used to specify where the listener should be added. The keys :before and :after are recognized and must contain a valid listener ID. If no key is or an unknown ID is specified, the listener is added as last entry in the listener array.



23
24
25
26
27
28
29
30
# File 'lib/webgen/blackboard.rb', line 23

def add_listener(msg_name, id = nil, position = {}, &block)
  position = if position[:before]
               (@listener[msg_name] || []).index {|lid, obj| lid == position[:before]}
             elsif position[:after]
               (pos = (@listener[msg_name] || []).index {|lid, obj| lid == position[:after]}) && pos + 1
             end
  insert_listener_at_position(msg_name, id, position || -1, &block)
end

#dispatch_msg(msg_name, *args) ⇒ Object

Dispatch the message msg_name to all listeners for this message, passing the given arguments.



51
52
53
54
# File 'lib/webgen/blackboard.rb', line 51

def dispatch_msg(msg_name, *args)
  return unless @listener[msg_name]
  @listener[msg_name].each {|id, obj| obj.call(*args)}
end

#remove_listener(msg_names, id) ⇒ Object

Remove the blocks associated with the given ID from the dispatcher queues of the given message names.



45
46
47
# File 'lib/webgen/blackboard.rb', line 45

def remove_listener(msg_names, id)
  [msg_names].flatten.each {|name| @listener[name].delete_if {|lid, b| lid == id} if @listener[name]}
end