Implements the Observable design pattern as a mixin so that other objects can be notified of changes in state. See observer.rb for details and an example.
Add observer as an observer on this object. observer will now receive notifications. The second optional argument specifies a method to notify updates, of which default value is update.
# File observer.rb, line 124
def add_observer(observer, func=:update)
@observer_peers = {} unless defined? @observer_peers
unless observer.respond_to? func
raise NoMethodError, "observer does not respond to `#{func.to_s}'"
end
@observer_peers[observer] = func
end
Set the changed state of this object. Notifications will be sent only if the changed state is true.
# File observer.rb, line 162
def changed(state=true)
@observer_state = state
end
Query the changed state of this object.
# File observer.rb, line 169
def changed?
if defined? @observer_state and @observer_state
true
else
false
end
end
Return the number of observers associated with this object.
# File observer.rb, line 150
def count_observers
if defined? @observer_peers
@observer_peers.size
else
0
end
end
Delete observer as an observer on this object. It will no longer receive notifications.
# File observer.rb, line 136
def delete_observer(observer)
@observer_peers.delete observer if defined? @observer_peers
end
Delete all observers associated with this object.
# File observer.rb, line 143
def delete_observers
@observer_peers.clear if defined? @observer_peers
end
If this object’s changed state is true, invoke the update method in each currently associated observer in turn, passing it the given arguments. The changed state is then set to false.
# File observer.rb, line 182
def notify_observers(*arg)
if defined? @observer_state and @observer_state
if defined? @observer_peers
@observer_peers.each { |k, v|
k.send v, *arg
}
end
@observer_state = false
end
end