aboutsummaryrefslogtreecommitdiffstats
path: root/activemodel/lib/active_model/validations_repair_helper.rb
blob: 99e3b2f631008d1ded92852cc210de3fa9707006 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
module ActiveModel
  module ValidationsRepairHelper
    def self.included(base)
      base.class_eval do
        extend ClassMethods
      end
    end

    module Toolbox
      def self.record_validations(*model_classes)
        model_classes.inject({}) do |repair, klass|
          repair[klass] ||= {}
          [:validate, :validate_on_create, :validate_on_update].each do |callback|
            the_callback = klass.instance_variable_get("@#{callback.to_s}_callbacks")
            repair[klass][callback] = (the_callback.nil? ? nil : the_callback.dup)
          end
          repair
        end
      end

      def self.reset_validations(recorded)
        recorded.each do |klass, repairs|
          [:validate, :validate_on_create, :validate_on_update].each do |callback|
            klass.instance_variable_set("@#{callback.to_s}_callbacks", repairs[callback])
          end
        end
      end
    end

    module ClassMethods
      def repair_validations(*model_classes)
        setup do
          @validation_repairs = Toolbox.record_validations(*model_classes)
        end
        teardown do
          Toolbox.reset_validations(@validation_repairs)
        end
      end
    end

    def repair_validations(*model_classes, &block)
      validation_repairs = Toolbox.record_validations(*model_classes)
      return block.call
    ensure
      Toolbox.reset_validations(validation_repairs)
    end
  end
end