From 36acac38c344478b52c755612e1ceaea334f40bb Mon Sep 17 00:00:00 2001 From: Thorsten Eckel Date: Wed, 3 May 2017 15:29:56 +0200 Subject: [PATCH] Added custom ActiveSupport callback helper do disable the execution of a given callback for a yielded block. --- .../lib/active_support/callbacks.rb | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 lib/core_ext/activesupport/lib/active_support/callbacks.rb diff --git a/lib/core_ext/activesupport/lib/active_support/callbacks.rb b/lib/core_ext/activesupport/lib/active_support/callbacks.rb new file mode 100644 index 000000000..9a70fd0e4 --- /dev/null +++ b/lib/core_ext/activesupport/lib/active_support/callbacks.rb @@ -0,0 +1,33 @@ +module ActiveSupport::Callbacks::ClassMethods + # Performs actions on a ActiveSupport model without triggering the given callback. + # The parameters are the same as for `skip_callback` and `set_callback`: + # http://api.rubyonrails.org/classes/ActiveSupport/Callbacks/ClassMethods.html + # + # Keep in mind that variables defined inside the block are only valid there. If you need + # to access one after the block has been processed make sure to initialize the variable + # before the block. This is the same behaviour as for all blocks. + # + # ATTENTION: This is not thread-safe and should not be used in threaded environment. + # + # @param name [Symbol] The name of the callback like e.g. :save + # @param when [Symbol] Indicates the time when the callback should run like e.g. :before + # @param method [Symbol] The name of the method that should get disabled e.g. :some_example_method + # + # @example + # User.without_callback(:create, :after, :avatar_for_email_check) do + # User.create(...) + # 'example return value' + # end + # #=> 'example return value' + # + # @return [optional] Returns the return value of the given block + def without_callback(*args) + begin + skip_callback(*args) + result = yield + ensure + set_callback(*args) + end + result + end +end