5 Apr
Observers: observing when changes have been made…
I wanted to find a solution that only sends an email to notify when a change has been made to the page. I came across the Observer. It works great when you need to compare if the value have been changed from before the save button to after.
This is how it works:
In the controller, add the following at the top of the page:
observer :mail_observer
and in the model, add the following to get the changed attributes:
attr_accessor :changed_attributes
Create a new model:
mail_observer.rb
Your mail_observer should look similar to this, I call two callback methods before_save and after_save:
class MailObserver < ActiveRecord::Observer #observe and the name of your model observe Task def before_save(model) #Place the old values into a hash table only if it is not a new record being inserted old_attr = Hash.new if !model.new_record? old_model = model.class.find(model.id) old_attr = old_model.attributes end tmp_diff = Hash.new #delete the values in the hash index where the values have not changed, leaving you with the changed values model.attributes.delete_if do |key,value| old_attr[key] == value end.keys.each do |k| tmp_diff[k] = old_attr[k] end model.changed_attributes = tmp_diff end
In the after_save function I check which values have changed by !model.changed_attributes[‘resource_name’].nil?, for the sake of example if a task that has been assigned to a person, is changed to another person, an email is sent to alert the new person that a task has been assigned to them.
#the after save function you have power to check which values have been changed and do something for it, depending on what has changed def after_save(model) #task resource_name if !model.changed_attributes['resource_name'].nil? #send an email to the person that has been assigned this of recent origin task puts 'the owner of this task is has been changed.' end end
This could be a good example to check when changes have been made to a page and to alert the changes that have been made.
