Module: Mongoid::Acts::Tree::InitializerMethods

Defined in:
lib/mongoid_acts_as_tree.rb

Instance Method Summary collapse

Instance Method Details

#acts_as_tree(options = {}) ⇒ Object



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
# File 'lib/mongoid_acts_as_tree.rb', line 13

def acts_as_tree(options = {})
	options = {
		:parent_id_field => "parent_id",
		:path_field      => "path",
		:depth_field     => "depth",
		:class           => self
	}.merge(options)

	class_attribute :acts_as_tree_options
	self.acts_as_tree_options = options

	include InstanceMethods
	include Fields
	extend Fields
	extend ClassMethods

	field parent_id_field, :type => BSON::ObjectId
	field path_field, :type => Array,  :default => [], :index => true
	field depth_field, :type => Integer, :default => 0

	self.class_eval do
		define_method "#{parent_id_field}=" do | new_parent_id |
		  if new_parent_id.present?
				new_parent = acts_as_tree_options[:class].find new_parent_id
				new_parent.children.push self, false
			else
				self.write_attribute parent_id_field, nil
				self[path_field] = []
				self[depth_field] = 0
		  end
		end
	end

	after_save      :move_children
	validate        :will_save_tree
	before_destroy  :destroy_descendants
end