Module: DataMapper::Is::Tree::ClassMethods

Defined in:
lib/dm_is_a_tree.rb

Overview

  • root - Returns the root of the current node (root when called on grandchild2)

Instance Method Summary collapse

Instance Method Details

#is_a_tree(options = {}) ⇒ Object Also known as: can_has_tree

Configuration options are:

  • foreign_key - specifies the column name to use for tracking of the tree (default: parent_id)

  • order - makes it possible to sort the children according to this SQL snippet.

  • counter_cache - keeps a count in a children_count column if set to true (default: false).



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/dm_is_a_tree.rb', line 57

def is_a_tree(options = {})
  configuration = { :foreign_key => "parent_id" }
  configuration.update(options) if options.is_a?(Hash)

  belongs_to :parent, :class_name => name, :foreign_key => configuration[:foreign_key], :counter_cache => configuration[:counter_cache]
  has_many :children, :class_name => name, :foreign_key => configuration[:foreign_key], :order => configuration[:order]

					include DataMapper::Is::Tree::InstanceMethods

					class_eval <<-CLASS
						def self.roots
							self.all :#{configuration[:foreign_key]} => nil, :order => #{configuration[:order].inspect}
						end

						def self.first_root
							self.first :#{configuration[:foreign_key]} => nil, :order => #{configuration[:order].inspect}
						end
					CLASS

					class << self
						alias_method :root, :first_root # for people used to the ActiveRecord acts_as_tree
					end
end