Module: ComfyPress::ActsAsTree::ClassMethods

Defined in:
lib/comfypress/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
# File 'lib/comfypress/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,
    :class_name     => name, 
    :foreign_key    => configuration[:foreign_key],
    :order          => configuration[:order],
    :dependent      => configuration[:dependent]
    
  class_eval "    include ComfyPress::ActsAsTree::InstanceMethods\n    \n    scope :roots,\n      :conditions => \"\#{configuration[:foreign_key]} IS NULL\",\n      :order      => \#{configuration[:order].nil? ? \"nil\" : %Q{\"\#{configuration[:order]}\"}}\n    \n    def self.root\n      roots.first\n    end\n    \n    validates_each \"\#{configuration[:foreign_key]}\" do |record, attr, value|\n      if value\n        if record.id == value\n          record.errors.add attr, \"cannot be it's own id\"\n        elsif record.descendants.map {|c| c.id}.include?(value)\n          record.errors.add attr, \"cannot be a descendant's id\"\n        end\n      end\n    end\n  EOV\n  \nend\n"