Class: Amoeba::Macros::HasMany

Inherits:
Base
  • Object
show all
Defined in:
lib/amoeba/macros/has_many.rb

Instance Method Summary collapse

Methods inherited from Base

inherited, #initialize, #remapped_relation_name

Constructor Details

This class inherits a constructor from Amoeba::Macros::Base

Instance Method Details

#follow(relation_name, association) ⇒ Object



4
5
6
7
8
9
10
# File 'lib/amoeba/macros/has_many.rb', line 4

def follow(relation_name, association)
  if @cloner.amoeba.clones.include?(relation_name.to_sym)
    follow_with_clone(relation_name)
  else
    follow_without_clone(relation_name, association)
  end
end

#follow_with_clone(relation_name) ⇒ Object



12
13
14
15
16
17
18
19
20
21
# File 'lib/amoeba/macros/has_many.rb', line 12

def follow_with_clone(relation_name)
  # This  is  a  M:M  "has many  through"  where  we
  # actually copy  and reassociate the  new children
  # rather than only maintaining the associations
  @old_object.__send__(relation_name).each do |old_obj|
    relation_name = remapped_relation_name(relation_name)
    # associate this new child to the new parent object
    @new_object.__send__(relation_name) << old_obj.amoeba_dup
  end
end

#follow_without_clone(relation_name, association) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/amoeba/macros/has_many.rb', line 23

def follow_without_clone(relation_name, association)
  # This is a regular 1:M "has many"
  #
  # copying the children of the regular has many will
  # effectively do what is desired anyway, the through
  # association is really just for convenience usage
  # on the model
  return if association.is_a?(ActiveRecord::Reflection::ThroughReflection)

  @old_object.__send__(relation_name).each do |old_obj|
    copy_of_obj = old_obj.amoeba_dup(@options)
    copy_of_obj[:"#{association.foreign_key}"] = nil
    relation_name = remapped_relation_name(relation_name)
    # associate this new child to the new parent object
    @new_object.__send__(relation_name) << copy_of_obj
  end
end