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.
Follow me on Twitter