Class: Nanoc::NotificationCenter

Inherits:
Object
  • Object
show all
Defined in:
lib/nanoc/base/notification_center.rb

Overview

Provides a way to send notifications between objects. It allows blocks associated with a certain notification name to be registered; these blocks will be called when the notification with the given name is posted.

It is a slightly different implementation of the Observer pattern; the table of subscribers is not stored in the observable object itself, but in the notification center.

Class Method Summary (collapse)

Class Method Details

+ (void) on(name, id = nil) {|*args| ... }

This method returns an undefined value.

Adds the given block to the list of blocks that should be called when the notification with the given name is received.

Parameters:

  • name (String, Symbol)

    The name of the notification that will cause the given block to be called.

  • id (String, Symbol, nil) (defaults to: nil)

    An identifier for the block. This is only used to be able to remove the block (using the remove method) later. Can be nil, but this is not recommended because it prevents the given notification block from being unregistered.

Yields:

  • (*args)

    Will be executed with the arguments passed to post



30
31
32
33
34
35
# File 'lib/nanoc/base/notification_center.rb', line 30

def on(name, id = nil, &block)
  initialize_if_necessary(name)

  # Add observer
  @notifications[name] << { :id => id, :block => block }
end

+ (void) post(name, *args)

This method returns an undefined value.

Posts a notification with the given name and the given arguments.

Parameters:

  • name (String, Symbol)

    The name of the notification that should be posted.

  • args

    Arguments that wil be passed to the blocks handling the notification.



46
47
48
49
50
51
52
53
# File 'lib/nanoc/base/notification_center.rb', line 46

def post(name, *args)
  initialize_if_necessary(name)

  # Notify all observers
  @notifications[name].each do |observer|
    observer[:block].call(*args)
  end
end

+ (void) remove(name, id)

This method returns an undefined value.

Removes the block with the given identifier from the list of blocks that should be called when the notification with the given name is posted.

Parameters:

  • name (String, Symbol)

    The name of the notification that should no longer be registered.

  • id (String, Symbol)

    The identifier of the block that should be removed.



66
67
68
69
70
71
# File 'lib/nanoc/base/notification_center.rb', line 66

def remove(name, id)
  initialize_if_necessary(name)

  # Remove relevant observers
  @notifications[name].reject! { |i| i[:id] == id }
end