Module: ComfortableMexicanSofa::ActsAsTree::ClassMethods

Defined in:
lib/comfortable_mexican_sofa/extensions/acts_as_tree.rb

Instance Method Summary collapse

Instance Method Details

#cms_acts_as_tree(options = {}) ⇒ Object



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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/comfortable_mexican_sofa/extensions/acts_as_tree.rb', line 8

def cms_acts_as_tree(options = {})
  configuration = {
    :foreign_key    => 'parent_id', 
    :order          => nil, 
    :counter_cache  => nil,
    :dependent      => :destroy,
    :touch          => false }
  configuration.update(options) if options.is_a?(Hash)
  
  belongs_to :parent,
    :class_name     => name, 
    :foreign_key    => configuration[:foreign_key],
    :counter_cache  => configuration[:counter_cache],
    :touch          => configuration[:touch]
    
  has_many :children,
    -> { order(configuration[:order])},
    :class_name     => name, 
    :foreign_key    => configuration[:foreign_key],
    :dependent      => configuration[:dependent]
    
  class_eval <<-EOV
    include ComfortableMexicanSofa::ActsAsTree::InstanceMethods
    
    scope :roots, -> {
      where("#{configuration[:foreign_key]} IS NULL").
      order(#{configuration[:order].nil? ? "nil" : %Q{"#{configuration[:order]}"}})
    }
    
    def self.root
      roots.first
    end
    
    validates_each "#{configuration[:foreign_key]}" do |record, attr, value|
      if value
        if record.id == value
          record.errors.add attr, "cannot be it's own id"
        elsif record.descendants.map {|c| c.id}.include?(value)
          record.errors.add attr, "cannot be a descendant's id"
        end
      end
    end
  EOV
  
end