Sunday, January 14, 2007

The Observer Pattern using 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
end


admin=Person.new
admin.name='vagmi'
admin.address='admin@somesite.com'

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

# the second observer
admin.observe :name do |old,newvalue|
puts 'there can be multiple observers'
end

admin.name='root'
#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.

1 comment:

Raúl said...

And how can a listener be removed?