Created
August 11, 2010 16:16
-
-
Save dfl/519245 to your computer and use it in GitHub Desktop.
mixin to selectively disable ActiveRecord callbacks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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