Skip to Content

The observer pattern with ruby meta voodoo

The ruby standard library already has an implementation for the observer pattern. The implementation of the pattern was not very rubyish. It seemed a direct implementation of the Java equivalent of it. Ruby is far more powerful.  This is the more rubyish version of the of the code goes something like this.

require 'observerext'

class Person
    include Observer #include the observer related methods
    observable :name,:address # the metavoodoo to create the accessor methods and fire events

# first observer
admin.observe :name do |old,newvalue|
    puts %{The administrator changed from #{old} to #{newvalue}}

# the second observer
admin.observe :name do |old,newvalue|
    puts 'there can be multiple observers'
#this prints the following statements
# > The administrator has changed from vagmi to root
# > there can be multiple observers

You can find the code for observerext.rb here. What I have basically done is to extend the Module class, which defines the observable method. The observable method injects the attributes’ getters and setters. The setter method notifies the observers if there are any. The Observer module does the leg work of registering and unregistering the blocks and the notifyobservers method. Update: Forgot to credit Greg Houston for explaining some of the ruby voodoo.

Be the first to leave a comment
You must be Logged on to comment or reply to a post.