Module: AttrRedactor::Adapters::ActiveRecord

Defined in:
lib/attr_redactor/adapters/active_record.rb

Class Method Summary collapse

Class Method Details

.extended(base) ⇒ Object

:nodoc:



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
# File 'lib/attr_redactor/adapters/active_record.rb', line 5

def self.extended(base) # :nodoc:
  base.class_eval do

    # https://github.com/attr-encrypted/attr_encrypted/issues/68
    alias_method :reload_without_attr_redactor, :reload
    def reload(*args, &block)
      result = reload_without_attr_redactor(*args, &block)
      self.class.redacted_attributes.keys.each do |attribute_name|
        instance_variable_set("@#{attribute_name}", nil)
      end
      result
    end

    def perform_attribute_assignment(method, new_attributes, *args)
      return if new_attributes.blank?

      send method, new_attributes.reject { |k, _|  self.class.redacted_attributes.key?(k.to_sym) }, *args
      send method, new_attributes.reject { |k, _| !self.class.redacted_attributes.key?(k.to_sym) }, *args
    end
    private :perform_attribute_assignment

    if ::ActiveRecord::VERSION::STRING > "3.1"
      alias_method :assign_attributes_without_attr_redactor, :assign_attributes
      def assign_attributes(*args)
        perform_attribute_assignment :assign_attributes_without_attr_redactor, *args
      end
    end

    alias_method :attributes_without_attr_redactor=, :attributes=
    def attributes=(*args)
      perform_attribute_assignment :attributes_without_attr_redactor=, *args
    end
  end
end