Skip to content

Instantly share code, notes, and snippets.

@samleb
Last active August 29, 2015 14:22
Show Gist options
  • Save samleb/8a66299609a07fbf49c8 to your computer and use it in GitHub Desktop.
Save samleb/8a66299609a07fbf49c8 to your computer and use it in GitHub Desktop.
module ActiveRecord
module CallbacksDisabler
extend ActiveSupport::Concern
delegate :callbacks_disabled?, :without_callbacks, to: 'self.class'
# `run_callbacks` is the core of ActiveSupport callbacks system: in order for a method `foo`
# to have its callbacks triggered when called, the implementation has to look like this:
#
# def foo
# run_callbacks(:foo) { do_something }
# end
#
# Overriding it so that it does a plain `yield` is enough to completely skip callbacks.
def run_callbacks(*)
if callbacks_disabled?
yield if block_given?
else
super
end
end
module ClassMethods
def disable_callbacks
@@disable_callbacks = true
end
def enable_callbacks
@@disable_callbacks = false
end
def callbacks_disabled?
@@disable_callbacks ||= false
end
def without_callbacks
disable_callbacks
yield
ensure
enable_callbacks
end
end
end
end
ActiveSupport.on_load(:active_record) do
ActiveRecord::Base.send(:include, ActiveRecord::CallbacksDisabler)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment