Skip to content

Instantly share code, notes, and snippets.

@dfl
Created August 11, 2010 16:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfl/519245 to your computer and use it in GitHub Desktop.
Save dfl/519245 to your computer and use it in GitHub Desktop.
mixin to selectively disable ActiveRecord callbacks
module Internaut
module ActiveRecord
module CallbackExtensions
def self.included(base) #:nodoc:
base.extend ClassMethods
base.class_eval do
class_inheritable_accessor :disabled_callbacks
self.disabled_callbacks = [] # set default to empty array
end
end
# overloaded callback method with hook to disable callbacks
def callback(method)
self.disabled_callbacks ||= [] # FIXME: this is a hack required because we don't inherit the default [] from AR::Base properly?!
if self.disabled_callbacks.include?( method.to_s ) # disable hook
# puts "#{self.class}##{method} \t- invoked but disabled"
return true
else
super
end
end
private :callback
module ClassMethods
def with_callbacks_disabled(*callbacks, &block)
# old_value = self.disabled_callbacks
self.disabled_callbacks = [*callbacks.map(&:to_s)]
yield
self.disabled_callbacks = [] # old_value
end
alias_method :with_callback_disabled, :with_callbacks_disabled
def with_all_callbacks_disabled &block
all_callbacks = %w[
before_create
before_validation
before_validation_on_create
before_validation_on_update
before_save
before_update
before_destroy
after_create
after_validation
after_validation_on_create
after_validation_on_update
after_save
after_update
after_destroy
]
with_callbacks_disabled *all_callbacks, &block
end
end
end
end
end
ActiveRecord::Base.send :include, Internaut::ActiveRecord::CallbackExtensions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment