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/comfortable_mexican_sofa/acts_as_tree.rb', line 8
def 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 <<-EOV
include ComfortableMexicanSofa::ActsAsTree::InstanceMethods
scope :roots,
:conditions => "#{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
|