Module: AbAdmin::Concerns::DeepCloneable

Defined in:
lib/ab_admin/concerns/deep_cloneable.rb

Instance Method Summary collapse

Instance Method Details

#check_assoc(assoc_method) ⇒ Object


47
48
49
50
# File 'lib/ab_admin/concerns/deep_cloneable.rb', line 47

def check_assoc(assoc_method)
  raise "Target has no association #{assoc_method}" unless assoc = self.class.reflect_on_association(assoc_method)
  assoc
end

#deep_dup(target, *args) ⇒ Object


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
# File 'lib/ab_admin/concerns/deep_cloneable.rb', line 9

def deep_dup(target, *args)
  dupl = target || self.dup

  args.reject! { |a| a.blank? }
  return dupl if args.empty?

  args.each do |arg|
    case arg
      when Hash
        arg.each do |k, v|
          dup_simple(dupl, k, v)
        end
      else
        Array(arg).each do |k|
          if k.kind_of?(Hash) || k.kind_of?(Array)
            self.deep_dup(dupl, k)
          else
            dup_simple(dupl, k)
          end
        end
    end
  end

  dupl
end

#deep_duplicate(*args) ⇒ Object


5
6
7
# File 'lib/ab_admin/concerns/deep_cloneable.rb', line 5

def deep_duplicate(*args)
  deep_dup(false, *args)
end

#dup_simple(dupl, k, v = nil) ⇒ Object


35
36
37
38
39
40
41
42
43
44
45
# File 'lib/ab_admin/concerns/deep_cloneable.rb', line 35

def dup_simple(dupl, k, v=nil)
  if check_assoc(k).collection?
    self.send(k).each do |rec|
      dupl.send(k) << (v ? rec.deep_dup(false, v) : rec.dup)
    end
  else
    dupl.send("#{k}=", (v ? self.send(k).deep_dup(false, v) : self.send(k).dup))
  end

  dupl
end