Module: ActiveRecord::Duplicate

Extended by:
ActiveSupport::Concern
Defined in:
lib/activerecord-duplicate/duplicate.rb,
lib/activerecord-duplicate/railtie.rb,
lib/activerecord-duplicate.rb

Defined Under Namespace

Modules: ClassMethods Classes: Railtie

Instance Method Summary collapse

Instance Method Details

#duplicateObject



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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/activerecord-duplicate/duplicate.rb', line 11

def duplicate
  self.duplication_context = :original
    self.run_callbacks(:duplication) do
    dup.tap do |duplicate|
      duplicate.duplication_context = :duplicate
      duplicate.run_callbacks(:duplication) do
        attributes.each do |key, value|
          value = case true
          
          # Duplicate attribute if whitelisted
          when self.class.attr_duplicatable?(key)
            value
          
          # If not whitelisted, set to default value
          when (column = self.class.columns.detect { |c| c.name == key }).present?
            column.default
          
          else
            nil
          end
          
          duplicate.send(:"#{key}=", value)
        end
        
        self.class.reflect_on_all_associations.each do |association|
          name = association.name
          
          next unless self.class.attr_duplicatable?(name)
          macro = association.macro
          association = self.association(association.name)
          
          case macro
          when :belongs_to
            # Duplicate all belongs_to associations.
            if duplication_parent.is_a?(association.klass)
              duplicate.send(:"#{name}=", duplication_parent)
              duplicate.send(:"#{name}_id=", nil)
            else
              duplicate.send(:"#{name}=", send(name))
            end
          
          when :has_many
            # Duplicate all has_many associations.
            duplicate.send(:"#{name}=", send(name).map do |object|
              object.duplication_parent = duplicate
              object = object.duplicate
              next unless object.present?
              
              object
            end.compact)
          end
        end
      end
    end
  end
end