How to Disable Callbacks on a Model

Does anyone know how to disable a model’s callbacks?

I have a routine that increments a page_view counter for various model
objects in an after_filter in my ApplicationController. I call this:
increment_page_view()

Rather that checking through the trace array in each model callback for
“increment_page_view” I’d rather disable the callbacks from inside
increment_page_view() itself.

Seems like it should be possible, but don’t seem to be able to work it
out.

Anybody done this or have ideas on how to do it?

Thanks :slight_smile:

You shouldn’t do this from the filter in the controller. It’s skating on
the
edge of breaking MVC.

Make your own model

class MyBase < ActiveRecord::Base
def before_save
end

def before_update
end

def before_create
end
end

Then inherit any of your models from that.

If you wanted to do this from outside of the model (which I don’t think
is
good because you are tying models to controllers) you could experiment
with
disabling the callbacks on an instance of your model by using a module.
I
have not tested this at all… just writing this off the top of my head.

lib/disable_callbacks.rb
module DisableCallbacks
def before_save
end

def before_update
end

def before_create
end
end

environment.rb

require ‘disable_callbacks’

your controller’s filter

def increment_page_view

include DisableCallbacks
@my_model = MyModel.find :first
@my_model.extend DisableCallbacks

end

Does any of that make sense?