Extended maintenance of Ruby versions 1.8.7 and 1.9.2 ended on July 31, 2014. Read more

In Files

  • observer.rb

Class/Module Index [+]



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.

Public Instance Methods

add_observer(observer, func=:update) click to toggle source

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}'"
  @observer_peers[observer] = func
changed(state=true) click to toggle source

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

Query the changed state of this object.

               # File observer.rb, line 169
def changed?
  if defined? @observer_state and @observer_state
count_observers() click to toggle source

Return the number of observers associated with this object.

               # File observer.rb, line 150
def count_observers
  if defined? @observer_peers
delete_observer(observer) click to toggle source

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

Delete all observers associated with this object.

               # File observer.rb, line 143
def delete_observers
  @observer_peers.clear if defined? @observer_peers
notify_observers(*arg) click to toggle source

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
    @observer_state = false

Commenting is here to help enhance the documentation. For example, code samples, or clarification of the documentation.

If you have questions about Ruby or the documentation, please post to one of the Ruby mailing lists. You will get better, faster, help that way.

If you wish to post a correction of the docs, please do so, but also file bug report so that it can be corrected for the next release. Thank you.

If you want to help improve the Ruby documentation, please visit Documenting-ruby.org.

blog comments powered by Disqus