Rails Observer Implementation Part 1

10 April 2012 by Amar Daximi 1 comment

Before starting Rails Observer implementation first we quickly go through how ruby observer library is implemented.

What is Observer Pattern?
The Observer pattern (also known as publish/subscribe) provides a simple mechanism for one object to inform a set of interested third-party objects when its state changes.

require "observer"

class Foo
 include Observable
 def initialize
  add_observer(ObserveFoo)
 end
 def foo
   changed
   puts "Before Observing Foo"
   notify_observers
   puts "After Observing Foo"
 end
end
class ObserveFoo
  def self.update
    puts "Observing foo"
  end
end
Foo.new.foo
#Output
#Before Observing Foo
#Observing foo
#After Observing Foo

In above example Object of foo is observerd by ObserveFoo.

Lets walk through how it’s implemented.

add_observer methods take 2 parameters, Class/Object and method name, that invokes after notification,by default update method is called.(in ruby 1.8.7 only one parameter with update function).
In this method it adds to @observer_peers hash where key is Class/Object and value is the method name.

When Object has changed its state hen we have to notify observers.

So state can be changed by invoking changed method. This sets @observer_state variable to true.

After that we can notify by calling notify_observers(*args). This method collects all observers associated with it and invokes respective method(which is registered at the time of adding observer) with the argument ,and changes the state to false for further notification.

So in ruby it’s simple to achieve Observer Pattern in almost 3 steps.

1) Add Observer which will track all observable object
2) Change the state
3) Notify Observer which will invoke all observable object method and changed state to false for further notification.

More info regarding ruby Observer you can visit here

In next post we quickly go through Active Model observer.

I hope it helps understanding ruby observer pattern better.

Comments and feedbacks are welcome.

Amar Daximi

Follow me on Twitter

1 thought on “Rails Observer Implementation Part 1”

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe To Our Blog

Get access to proven marketing ideas, latest trends and best practices.

Next up home

Contact

Lets build cool stuff

Share your contact information & we will get in touch!

I want (Tell us more about your dream project)