DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Creating New Observable Methods For An ActiveRecord Model

06.01.2005
| 5304 views |
  • submit to reddit
        Once in awhile, the AR observable callbacks are just not enough, and you need more!  In this example, I'll set the observer to watch when a developer is added to a project.

Observer code:
class ProjectObserver < ActiveRecord::Observer
  def new_update(callback_method, object, developer = nil)
    if developer
      send(callback_method, object, developer) if respond_to?(callback_method)
    else 
      old_update(callback_method, object)
    end
  end
  alias_method :old_update, :update
  alias_method :update, :new_update

  def before_add_developer(project, developer)
    puts "Adding #{developer}..."
  end
  
  def after_add_developer(project, developer)
    puts "Added #{developer}..."
  end
  
  def after_save(project)
    puts "Project saved..."
  end
end

Model:

class Project < ActiveRecord::Base
  has_and_belongs_to_many :developers

  def add_developer(developer)
    self.class.changed
    self.class.notify_observers(:before_add_developer, self, developer)
    transaction do
      self.developers << developer
      self.save
    end
    self.class.changed
    self.class.notify_observers(:after_add_developer, self, developer)
  end
end

It would be great if I could override the self.developers#<< method instead...