Sha256: 86d2e556a735f1bdc44ea486c93027a703689524c7c2d12197fcd1badd8e4041

Contents?: true

Size: 1.29 KB

Versions: 10

Compression:

Stored size: 1.29 KB

Contents

require 'active_support/basic_object'

ActiveRecord::Base.class_eval do
  class WithoutCallbacks < ActiveSupport::BasicObject
    def initialize(target, types)
      @target = target
      @types  = types
    end

    def respond_to?(method, include_private = false)
      @target.respond_to?(method, include_private)
    end

    def method_missing(method, *args, &block)
      @target.skip_callbacks(*@types) do
        @target.send(method, *args, &block)
      end
    end
  end

  class << self
    def without_callbacks(*types)
      WithoutCallbacks.new(self, types)
    end

    def skip_callbacks(*types)
      deactivate_callbacks(*types)
      yield.tap do
        activate_callbacks(*types)
      end
    end

    def deactivate_callbacks(*types)
      types = [:save, :create, :update, :destroy, :touch] if types.empty?
      types.each do |type|
        name = :"_run_#{type}_callbacks"
        alias_method(:"_deactivated_#{name}", name)
        define_method(name) { |&block| block.call }
      end
    end

    def activate_callbacks(*types)
      types = [:save, :create, :update, :destroy, :touch] if types.empty?
      types.each do |type|
        name = :"_run_#{type}_callbacks"
        alias_method(name, :"_deactivated_#{name}")
        undef_method(:"_deactivated_#{name}")
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
adva-core-0.0.14 lib/core_ext/rails/active_record/skip_callbacks.rb
adva-core-0.0.13 lib/core_ext/rails/active_record/skip_callbacks.rb
adva-core-0.0.9 lib/core_ext/rails/active_record/skip_callbacks.rb
adva-core-0.0.8 lib/core_ext/rails/active_record/skip_callbacks.rb
adva-core-0.0.7 lib/core_ext/rails/active_record/skip_callbacks.rb
adva-core-0.0.6 lib/core_ext/rails/active_record/skip_callbacks.rb
adva-core-0.0.5 lib/core_ext/rails/active_record/skip_callbacks.rb
adva-core-0.0.4 lib/core_ext/rails/active_record/skip_callbacks.rb
adva-core-0.0.2 lib/core_ext/rails/active_record/skip_callbacks.rb
adva-core-0.0.1 lib/core_ext/rails/active_record/skip_callbacks.rb