Module: ActiveRecord::Acts::Tree::InstanceMethods

Defined in:
lib/active_record/acts/tree.rb

Instance Method Summary collapse

Instance Method Details

#ancestorsObject

Returns list of ancestors, starting from parent until root.

subchild1.ancestors # => [child1, root]


114
115
116
117
# File 'lib/active_record/acts/tree.rb', line 114

def ancestors
  node, nodes = self, []
  nodes << node = node.parent until node.parent.nil? and return nodes
end

#childlessObject



161
162
163
# File 'lib/active_record/acts/tree.rb', line 161

def childless
  self.descendants.collect{|d| d.children.empty? ? d : nil}.compact
end

#descendants(node = self) ⇒ Object

Returns a flat list of the descendants of the current node.

root.descendants # => [child1, subchild1, subchild2]


150
151
152
153
154
155
156
157
158
159
# File 'lib/active_record/acts/tree.rb', line 150

def descendants(node=self)
  nodes = []
  nodes << node unless node == self
  
  node.children.each do |child|
    nodes += descendants(child)
  end
    
  nodes.compact
end

#leaf?Boolean

Returns:

  • (Boolean)


123
124
125
# File 'lib/active_record/acts/tree.rb', line 123

def leaf?
  children.length == 0
end

#rootObject

Returns the root node of the tree.



128
129
130
131
# File 'lib/active_record/acts/tree.rb', line 128

def root
  node = self
  node = node.parent until node.parent.nil? and return node
end

#root?Boolean

Returns:

  • (Boolean)


119
120
121
# File 'lib/active_record/acts/tree.rb', line 119

def root?
  parent == nil
end

#self_and_siblingsObject

Returns all siblings and a reference to the current node.

subchild1.self_and_siblings # => [subchild1, subchild2]


143
144
145
# File 'lib/active_record/acts/tree.rb', line 143

def self_and_siblings
  parent ? parent.children : self.class.roots
end

#siblingsObject

Returns all siblings of the current node.

subchild1.siblings # => [subchild2]


136
137
138
# File 'lib/active_record/acts/tree.rb', line 136

def siblings
  self_and_siblings - [self]
end