Module: MongoMapper::Plugins::ActsAsTree::ClassMethods

Defined in:
lib/mongo_mapper/plugins/acts_as_tree.rb

Overview


Instance Method Summary collapse

Instance Method Details

#acts_as_tree(options = {}) ⇒ Object



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
54
# File 'lib/mongo_mapper/plugins/acts_as_tree.rb', line 11

def acts_as_tree(options = {})
  configuration = { :foreign_key => :parent_id, :order => nil }
  configuration.update(options) if options.is_a?(Hash)

  # automatically create needed keys if they don't already exist
  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]
  many :children, :class_name => name, :foreign_key => configuration[:foreign_key], :order => configuration[:order], :dependent => :destroy

  before_save :set_parents

  class_eval "    def self.roots\n      where(\"\#{configuration[:foreign_key]}\".to_sym => nil).sort(\"\#{configuration[:order]}\").all\n    end\n\n    def self.root\n      where(\"\#{configuration[:foreign_key]}\".to_sym => nil).sort(\"\#{configuration[:order]}\").first\n    end\n\n    def set_parents\n      self.\#{configuration[:foreign_key].to_s.pluralize} = parent.\#{configuration[:foreign_key].to_s.pluralize}.dup << \#{configuration[:foreign_key]} if parent?\n    end\n    \n    def ancestors\n      self.class.where(:id => { '$in' => self.\#{configuration[:foreign_key].to_s.pluralize} }).all.reverse || []\n    end\n    \n    def root\n      self.class.find(self.\#{configuration[:foreign_key].to_s.pluralize}.first) || self\n    end\n    \n    def descendants\n      self.class.where('\#{configuration[:foreign_key].to_s.pluralize}' => self.id).all\n    end\n    \n    def depth\n      self.\#{configuration[:foreign_key].to_s.pluralize}.count\n    end\n    \n  EOV\nend\n"