Class: Nanoc::Core::NotificationCenter
- Inherits:
-
Object
- Object
- Nanoc::Core::NotificationCenter
- Defined in:
- lib/nanoc/core/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
- .instance ⇒ Object
- .on(name, id = nil) ⇒ Object
- .post(name) ⇒ Object
- .remove(name, id) ⇒ Object
- .reset ⇒ Object
Instance Method Summary collapse
-
#initialize ⇒ NotificationCenter
constructor
A new instance of NotificationCenter.
- #on(name, id = nil, &block) ⇒ Object
- #post(name, *args) ⇒ Object
- #remove(name, id) ⇒ Object
Constructor Details
#initialize ⇒ NotificationCenter
Returns a new instance of NotificationCenter.
13 14 15 16 |
# File 'lib/nanoc/core/notification_center.rb', line 13 def initialize # name => observers dictionary @notifications = Hash.new { |hash, name| hash[name] = [] } end |
Class Method Details
.instance ⇒ Object
35 36 37 |
# File 'lib/nanoc/core/notification_center.rb', line 35 def instance @_instance ||= new end |
.on(name, id = nil) ⇒ Object
39 40 41 |
# File 'lib/nanoc/core/notification_center.rb', line 39 def on(name, id = nil, &) instance.on(name, id, &) end |
.post(name) ⇒ Object
43 44 45 |
# File 'lib/nanoc/core/notification_center.rb', line 43 def post(name, *) instance.post(name, *) end |
.remove(name, id) ⇒ Object
47 48 49 |
# File 'lib/nanoc/core/notification_center.rb', line 47 def remove(name, id) instance.remove(name, id) end |
.reset ⇒ Object
51 52 53 |
# File 'lib/nanoc/core/notification_center.rb', line 51 def reset @_instance = nil end |
Instance Method Details
#on(name, id = nil, &block) ⇒ Object
18 19 20 |
# File 'lib/nanoc/core/notification_center.rb', line 18 def on(name, id = nil, &block) @notifications[name] << { id:, block: } end |
#post(name, *args) ⇒ Object
26 27 28 29 30 31 32 |
# File 'lib/nanoc/core/notification_center.rb', line 26 def post(name, *args) @notifications[name].each do |observer| observer[:block].call(*args) end self end |
#remove(name, id) ⇒ Object
22 23 24 |
# File 'lib/nanoc/core/notification_center.rb', line 22 def remove(name, id) @notifications[name].reject! { |i| i[:id] == id } end |