Module: Occams::Extensions::ActsAsTree::InstanceMethods

Defined in:
lib/occams/extensions/acts_as_tree.rb

Instance Method Summary collapse

Instance Method Details

#ancestorsObject

Returns list of ancestors, starting from parent until root.

subchild1.ancestors # => [child1, root]


61
62
63
64
65
66
# File 'lib/occams/extensions/acts_as_tree.rb', line 61

def ancestors
  node  = self
  nodes = []
  nodes << node = node.parent while node.parent
  nodes
end

#descendantsObject

Returns all children and children of children



69
70
71
72
73
74
75
76
# File 'lib/occams/extensions/acts_as_tree.rb', line 69

def descendants
  nodes = []
  children.each do |c|
    nodes << c
    nodes << c.descendants
  end
  nodes.flatten
end

#parent_id=(id) ⇒ Object

BUG: github.com/rails/rails/issues/14369 It’s still a bug. Remove it to see failing test



106
107
108
# File 'lib/occams/extensions/acts_as_tree.rb', line 106

def parent_id=(id)
  self.parent = self.class.find_by(id: id)
end

#rootObject

Returns the root node of the tree.



79
80
81
82
83
# File 'lib/occams/extensions/acts_as_tree.rb', line 79

def root
  node = self
  node = node.parent while node.parent
  node
end

#root?Boolean

Checks if this node is a root

Returns:

  • (Boolean)


86
87
88
# File 'lib/occams/extensions/acts_as_tree.rb', line 86

def root?
  !parent_id
end

#self_and_siblingsObject

Returns all siblings and a reference to the current node.

subchild1.self_and_siblings # => [subchild1, subchild2]


100
101
102
# File 'lib/occams/extensions/acts_as_tree.rb', line 100

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

#siblingsObject

Returns all siblings of the current node.

subchild1.siblings # => [subchild2]


93
94
95
# File 'lib/occams/extensions/acts_as_tree.rb', line 93

def siblings
  self_and_siblings - [self]
end