Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Creating New Observable Methods For An ActiveRecord Model

DZone's Guide to

Creating New Observable Methods For An ActiveRecord Model

·
Free Resource
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...  
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}