Rails Observer


What is observer?

Observer serves as a connection point between models and some other subsystem whose functionality is used by some of other classes, such as email notification. It is loose coupling in contract with model callback.

When should we use?

If your model code gets too messy start to think about using observers for some unessential behavior. The real power (at least as I see it) of observers lies in their ability to serve as a connection point between your models and some other subsystem whose functionality is used by all (or some) of the other classes. Let’s say you decide to add an IM notification to your application – say you want to be notified about some (or all) of the CRUD actions of some (or all) of the models in your system. In this case using observers would be ideal – your notification subsystem will stay perfectly separated from your business logic and your models won’t be cluttered with behavior which is not of their business. Another good use case for observers would be an auditing subsystem.

Observer

$rails g observer EmailNotification

class EmailNotificationObserver < ActiveRecord::Observer
  observe :order, :address
 
  def after_create(model)    
      if model.class.name == “Order”
        Notifier.order_created.deliver
    else
        Notifier.address_created.deliver    
    end    
  end
end

Notifier Model:

class Notifier < ActionMailer::Base

    #layout “notifier”    
    
  default from: “test12@gmail.com”
 
  def order_created
    mail(:to => ‘mpravin@gmail.com’, :subject => “Order”) do |format|
        format.html {render :layout => ‘notifier’}        
    end
  end
 
  def address_created
    mail(:to => ‘mpravin@gmail.com‘, :subject => “Address”)    
  end
 
end

Cheers!