| Module | Publisher |
| In: |
lib/utility/publisher.rb
|
Publisher is a variation on Ruby‘s Observable. We do not keep track of any changed state; instead we assume that by virtue of calling publish we have changed state. We do not allow serialization of subscribers. We allow a Publisher to have multiple publications and maintain separate lists of subscribers for each one.
If this object‘s changed state is true, invoke the update method in each currently associated subscriber in turn, passing it the given arguments. The changed state is then set to false.
# File lib/utility/publisher.rb, line 65 def publish(*arg) if defined? @subscribers @subscribers.dup.each do |s| if s.respond_to?(:to_int) Engine.instance.db.get(s).update(*arg) else s.update(*arg) end end end end
Add subscriber as an subscriber on this object. subscriber will now receive notifications.
# File lib/utility/publisher.rb, line 30 def subscribe(subscriber) @subscribers ||= [] if !subscriber.respond_to?(:to_int) && !subscriber.respond_to?(:update) raise NoMethodError, "subscriber needs to respond to 'update'" end @subscribers.push subscriber end
Count of subscribers to this object.
# File lib/utility/publisher.rb, line 56 def subscriber_count @subscribers ? @subscribers.size : 0 end
Delete subscriber as a subscriber on this object. It will no longer receive notifications.
# File lib/utility/publisher.rb, line 42 def unsubscribe(subscriber) @subscribers.delete subscriber if defined? @subscribers end