Module: ActsAsAggregateRoot::ClassMethods

Defined in:
lib/acts_as_aggregate_root/acts_as_aggregate_root.rb

Instance Method Summary collapse

Instance Method Details

#acts_as_aggregate_rootObject



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/acts_as_aggregate_root/acts_as_aggregate_root.rb', line 7

def acts_as_aggregate_root
  
  def add_destroy_methods_to_class(klass)
    klass.reflections.select {|(k,v)| v.macro == :has_many }.each {|(name,reflection)|
       add_destroy_method(klass,name.to_s)
       reflection.options[:autosave] = true
       add_destroy_methods_to_class(reflection.klass)
    }
  end


  def add_destroy_method(klass,reflection_name)
    klass.instance_eval do
      method_name = "has_many_dependent_destroy_for_#{reflection_name}".to_sym
      define_method(method_name) do
        send(reflection_name).each { |o| o.destroy }
      end
      before_destroy method_name
    end 
  end 

  self.instance_eval do
    def has_many(association_id, options = {}, &extension)
      # options .merge! :autosave => true , :dependent => :destroy 
      super
      reflection = create_has_many_reflection(association_id, options, &extension)
      reflection.options[:autosave] = true
      add_destroy_method(self,reflection.name)
      add_destroy_methods_to_class(reflection.klass)
    end
  end
end

#add_destroy_method(klass, reflection_name) ⇒ Object



18
19
20
21
22
23
24
25
26
# File 'lib/acts_as_aggregate_root/acts_as_aggregate_root.rb', line 18

def add_destroy_method(klass,reflection_name)
  klass.instance_eval do
    method_name = "has_many_dependent_destroy_for_#{reflection_name}".to_sym
    define_method(method_name) do
      send(reflection_name).each { |o| o.destroy }
    end
    before_destroy method_name
  end 
end

#add_destroy_methods_to_class(klass) ⇒ Object



9
10
11
12
13
14
15
# File 'lib/acts_as_aggregate_root/acts_as_aggregate_root.rb', line 9

def add_destroy_methods_to_class(klass)
  klass.reflections.select {|(k,v)| v.macro == :has_many }.each {|(name,reflection)|
     add_destroy_method(klass,name.to_s)
     reflection.options[:autosave] = true
     add_destroy_methods_to_class(reflection.klass)
  }
end