Class: Nanoc3::NotificationCenter

Inherits:
Object
  • Object
show all
Defined in:
lib/nanoc3/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.

cause the given block to be called.

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.

Parameters:

  • name (String, Symbol)

    The name of the notification that will

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

    An identifier for the block. This is

Yields:

  • (*args)

    Will be executed with the arguments passed to post



30
31
32
33
34
35
# File 'lib/nanoc3/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.

be posted.

notification.

Parameters:

  • name (String, Symbol)

    The name of the notification that should

  • args

    Arguments that wil be passed to the blocks handling the



46
47
48
49
50
51
52
53
# File 'lib/nanoc3/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.

no longer be registered.

removed.

Parameters:

  • name (String, Symbol)

    The name of the notification that should

  • id (String, Symbol)

    The identifier of the block that should be



66
67
68
69
70
71
# File 'lib/nanoc3/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