class Nanoc::Core::NotificationCenter
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.
Constants
- DONE
- SYNC
Public Class Methods
force_reset()
click to toggle source
# File lib/nanoc/core/notification_center.rb, line 95 def force_reset instance.force_stop @_instance = nil end
instance()
click to toggle source
# File lib/nanoc/core/notification_center.rb, line 74 def instance @_instance ||= new.tap(&:start) end
new()
click to toggle source
# File lib/nanoc/core/notification_center.rb, line 16 def initialize @thread = nil # name => observers dictionary @notifications = Hash.new { |hash, name| hash[name] = [] } @queue = Queue.new @sync_queue = Queue.new on(SYNC, self) { @sync_queue << true } end
on(name, id = nil, &block)
click to toggle source
# File lib/nanoc/core/notification_center.rb, line 78 def on(name, id = nil, &block) instance.on(name, id, &block) end
post(name, *args)
click to toggle source
# File lib/nanoc/core/notification_center.rb, line 82 def post(name, *args) instance.post(name, *args) end
remove(name, id)
click to toggle source
# File lib/nanoc/core/notification_center.rb, line 86 def remove(name, id) instance.remove(name, id) end
reset()
click to toggle source
# File lib/nanoc/core/notification_center.rb, line 90 def reset instance.stop @_instance = nil end
sync()
click to toggle source
# File lib/nanoc/core/notification_center.rb, line 100 def sync instance.sync end
Public Instance Methods
force_stop()
click to toggle source
# File lib/nanoc/core/notification_center.rb, line 51 def force_stop @queue << DONE end
on(name, id = nil, &block)
click to toggle source
# File lib/nanoc/core/notification_center.rb, line 55 def on(name, id = nil, &block) @notifications[name] << { id: id, block: block } end
post(name, *args)
click to toggle source
# File lib/nanoc/core/notification_center.rb, line 63 def post(name, *args) @queue << [name, args] self end
remove(name, id)
click to toggle source
# File lib/nanoc/core/notification_center.rb, line 59 def remove(name, id) @notifications[name].reject! { |i| i[:id] == id } end
start()
click to toggle source
# File lib/nanoc/core/notification_center.rb, line 28 def start @thread ||= Thread.new do Thread.current.abort_on_exception = true loop do elem = @queue.pop break if DONE.equal?(elem) name = elem[0] args = elem[1] @notifications[name].each do |observer| observer[:block].call(*args) end end end end
stop()
click to toggle source
# File lib/nanoc/core/notification_center.rb, line 46 def stop @queue << DONE @thread.join end
sync()
click to toggle source
# File lib/nanoc/core/notification_center.rb, line 68 def sync post(SYNC) @sync_queue.pop end