Last week, I wrote about the Singleton pattern in Ruby much like Rusty Divine did about Java/C#/.NET at CodeSnipers. Since his second entry was about the Observer pattern, I thought I’d write about its Ruby implementation.
The key ideas around the Ruby implementation of the Observer pattern are:
- Require the observer library
- Mixin the Observable module to your class which can be observed
- In the class that does the observing, implement the update method
That’s it.
Of course, an example would be nice. Here’s a small one.
require 'observer' # Key step 1
class MyObservableClass
include Observable # Key step 2
def blah
changed # note that our state has changed
notify_observers( 5 )
end
end
class MyObserverClass
def update(new_data) # Key step 3
puts "The new data is #{new_data}"
end
end
watcher = MyObservableClass.new
watcher.add_observer(MyObserverClass.new)
Now, any time that MyObservableClass#blah is called, the observing classes will get notified. In this example, we aren’t dynamically changing the data (in fact, it always stays constant), but I think you can see that if in fact the data DID change, the observers would all get notified of that change.

Small typo, link to
http://www.oreillynet.com/ruby/blog/2006/01/design_patterns_singleton.html
has a `"` on the end causing the link to fail.