Design Patterns - Observer in Ruby

Last week, I wrote about the Singleton pattern in Ruby much like Rusty Divine did about Java/C#/.NET. 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:

  1. Require the observer library
  2. Mixin the Observable module to your class which can be observed
  3. 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.