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
53
|
# File 'lib/mongo_mapper/plugins/acts_as_tree.rb', line 11
def acts_as_tree(options = {})
configuration = { :foreign_key => :parent_id, :order => nil, :counter_cache => nil }
configuration.update(options) if options.is_a?(Hash)
key configuration[:foreign_key], ObjectId unless keys.key?(configuration[:foreign_key])
key configuration[:foreign_key].to_s.pluralize.to_sym, Array unless keys.key?(configuration[:foreign_key].to_s.pluralize.to_sym)
belongs_to :parent, :class_name => name, :foreign_key => configuration[:foreign_key], :counter_cache => configuration[:counter_cache]
many :children, :class_name => name, :foreign_key => configuration[:foreign_key], :order => configuration[:order], :dependent => :destroy
before_save :set_parents
class_eval <<-EOV
def self.roots
where("#{configuration[:foreign_key]}".to_sym => nil).sort("#{configuration[:order]}").all
end
def self.root
where("#{configuration[:foreign_key]}".to_sym => nil).sort("#{configuration[:order]}").first
end
def set_parents
self.#{configuration[:foreign_key].to_s.pluralize} = parent.#{configuration[:foreign_key].to_s.pluralize}.dup << #{configuration[:foreign_key]} if parent?
end
def ancestors
self.class.where(:id => { '$in' => self.#{configuration[:foreign_key].to_s.pluralize} }).all.reverse || []
end
def root
self.class.find(self.#{configuration[:foreign_key].to_s.pluralize}.first) || self
end
def descendants
self.class.where('#{configuration[:foreign_key].to_s.pluralize}' => self.id).all
end
def depth
self.#{configuration[:foreign_key].to_s.pluralize}.count
end
EOV
end
|