module Publisher

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.

Public Instance Methods

publish(*arg) click to toggle source

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
subscribe(subscriber) click to toggle source

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
subscriber_count() click to toggle source

Count of subscribers to this object.

# File lib/utility/publisher.rb, line 56
def subscriber_count
  @subscribers ? @subscribers.size : 0
end
unsubscribe(subscriber) click to toggle source

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
unsubscribe_all() click to toggle source

Delete all subscribers associated with this object.

# File lib/utility/publisher.rb, line 49
def unsubscribe_all
  @subscribers.clear if defined? @subscribers
end