class Webgen::Blackboard
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.
Public Class Methods
Create a new Blackboard
object.
# File lib/webgen/blackboard.rb 11 def initialize 12 @listener = {} 13 end
Public Instance Methods
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.
# File lib/webgen/blackboard.rb 22 def add_listener(msg_name, id = nil, position = {}, &block) 23 position = if position[:before] 24 (@listener[msg_name] || []).index {|lid, obj| lid == position[:before]} 25 elsif position[:after] 26 (pos = (@listener[msg_name] || []).index {|lid, obj| lid == position[:after]}) && pos + 1 27 end 28 insert_listener_at_position(msg_name, id, position || -1, &block) 29 end
Dispatch the message msg_name
to all listeners for this message, passing the given arguments.
# File lib/webgen/blackboard.rb 50 def dispatch_msg(msg_name, *args) 51 return unless @listener[msg_name] 52 @listener[msg_name].each {|id, obj| obj.call(*args)} 53 end
Remove the blocks associated with the given ID from the dispatcher queues of the given message names.
# File lib/webgen/blackboard.rb 44 def remove_listener(msg_names, id) 45 [msg_names].flatten.each {|name| @listener[name].delete_if {|lid, b| lid == id} if @listener[name]} 46 end
Private Instance Methods
Insert the block as listener for msg_name
with the given id
at the position
in the listener array.
# File lib/webgen/blackboard.rb 33 def insert_listener_at_position(msg_name, id, position, &block) 34 if !block.nil? 35 (@listener[msg_name] ||= []).insert(position, [id, block]) 36 else 37 raise ArgumentError, "You have to provide a block" 38 end 39 end