Article

Skipping Active Record Callbacks

Posted  by Blake Watters.

PublicCategorized as Software Development.

Tagged with rails.

The following code will allow you to skip an ActiveRecord callback for the duration of the block. This can be useful if you are, for instance, building a model security layer and need to sidestep your enforcement callbacks temporarily.

  def skip_callback(callback, &block)
      method = instance_method(callback)
      remove_method(callback) if respond_to?(callback)
      define_method(callback) { true }
      yield
      remove_method(callback)
      define_method(callback, method)
  end

Usage:

  class User < ActiveRecord::Base
    before_save :raise_error

def raise_error
     raise 'You wont see me!'
  end
end
User.skip_callback(:raise_error) do
  user.save!
end

Arrow_down Hide comments

Powered by Strategy-NetsTerms of Services | Privacy Policy | Security Policy |