Module: ComfortableMexicanSofa::ActsAsTree::InstanceMethods

Defined in:
lib/comfortable_mexican_sofa/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]

65
66
67
68
69
70
# File 'lib/comfortable_mexican_sofa/extensions/acts_as_tree.rb', line 65

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

#descendantsObject

Returns all children and children of children


73
74
75
76
77
78
79
80
# File 'lib/comfortable_mexican_sofa/extensions/acts_as_tree.rb', line 73

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


110
111
112
# File 'lib/comfortable_mexican_sofa/extensions/acts_as_tree.rb', line 110

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

#rootObject

Returns the root node of the tree.


83
84
85
86
87
# File 'lib/comfortable_mexican_sofa/extensions/acts_as_tree.rb', line 83

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

#root?Boolean

Checks if this node is a root

Returns:

  • (Boolean)

90
91
92
# File 'lib/comfortable_mexican_sofa/extensions/acts_as_tree.rb', line 90

def root?
  !parent_id
end

#self_and_siblingsObject

Returns all siblings and a reference to the current node.

subchild1.self_and_siblings # => [subchild1, subchild2]

104
105
106
# File 'lib/comfortable_mexican_sofa/extensions/acts_as_tree.rb', line 104

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

#siblingsObject

Returns all siblings of the current node.

subchild1.siblings # => [subchild2]

97
98
99
# File 'lib/comfortable_mexican_sofa/extensions/acts_as_tree.rb', line 97

def siblings
  self_and_siblings - [self]
end