feat-shamwow.jpg

Remember my post from a few weeks back about temporarily disabling ActiveRecord callbacks?  Well, I decided to extend the functionality a bit and wrap it all up in a plugin.

You can now specify one or more callbacks to disable, or specify nothing and disable all callbacks by default.

You can check out the project page or jump over to the Github repo.

Comments (0)    git rails active_record callbacks plugin

ActiveRecord callbacks can be super-handy, but every once in a while, they get in the way.

I was recently working on an Intridea client project and I had to create a rake task to import a large set of data from a spreadsheet.  One of the models that was being imported had an after_save callback that sent out an email notification.  I didn't really want 3500 emails to be sent out whenever this rake task was ran, so I needed to disable the callback while the import task was running.

A former coworker, Blake, from NT showed me this trick...

Say you've got a model like so...

class Thing < ActiveRecord::Base
  before_save :do_stuff

  def do_stuff
    raise "This thing is doing stuff..."
  end
end

In the config/initializers directory, I created a file called extensions.rb.  You can call it whatever you like.  I chose 'extensions' because I use the same file for any minor Ruby or Rails class extensions.  In it, I put this...

class ActiveRecord::Base
  def self.without_callback(callback, &block)
    method = self.send(:instance_method, callback)
    self.send(:remove_method, callback)
    self.send(:define_method, callback) {true}
    yield
    self.send(:remove_method, callback)
    self.send(:define_method, callback, method)
  end
end

What this does is it grabs the callback and stores it in the method variable.  Remember, this code only circumvents the 'do_stuff' method, not anything declared as a before_save callback.  It then redefines the method to merely return true, yields to the block, and then redifines the the method with the contents of the method variable. 

Yielding to the block allows you to not have to worry about maintaining the method contents, or restoring it once you're done.  Also, if you were so inclined, you could easily modify this code to accept an array of method names and disable all of them

Once the extension is in place, you can do this...

Thing.without_callback(:do_stuff) do
  thing = Thing.new
  thing.save
end

...without 'do_stuff' ever being called.

Some people will probably argue that if you need to disable your callback, then your model should be defined differently, but I say that's bullshit.  I think this is perfectly acceptable in many cases.  Granted you probably wouldn't want to do this all throughout your application code, but I see no problem with using this technique in a test, or data migration, or in my case, a rake task.

[UPDATE]

WOOT! Now there's a plugin. Check it out... without_callbacks

Comments (0)    active_record callbacks