In Files

  • observer.rb

Class/Module Index [+]

Quicksearch

Observable

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}'"
  end
  @observer_peers[observer] = func
end
            
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
end
            
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
    true
  else
    false
  end
end
            
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
    @observer_peers.size
  else
    0
  end
end
            
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
end
            
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
end
            
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
  }
    end
    @observer_state = false
  end
end