Class: BasicTree

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/basic_tree.rb

Constant Summary collapse

VERSION =
"1.0.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object, parent = nil, &block) ⇒ BasicTree

Returns a new instance of BasicTree.



7
8
9
10
11
12
13
14
# File 'lib/basic_tree.rb', line 7

def initialize(object, parent = nil, &block)
  self.object = object
  if parent
    self.parent = parent
    parent.children << self
  end
  instance_eval(&block) if block_given?
end

Instance Attribute Details

#objectObject

Returns the value of attribute object.



16
17
18
# File 'lib/basic_tree.rb', line 16

def object
  @object
end

#parentObject

Returns the value of attribute parent.



16
17
18
# File 'lib/basic_tree.rb', line 16

def parent
  @parent
end

Instance Method Details

#add(object, &block) ⇒ Object



18
19
20
# File 'lib/basic_tree.rb', line 18

def add(object, &block)
  self.class.new(object, self, &block)
end

#ancestorsObject



26
27
28
# File 'lib/basic_tree.rb', line 26

def ancestors
  root? ? [] : (parent.ancestors << parent)
end

#childrenObject



58
59
60
# File 'lib/basic_tree.rb', line 58

def children
  @children ||= []
end

#descendantsObject



30
31
32
# File 'lib/basic_tree.rb', line 30

def descendants
  children.map { |c| [c] + c.descendants }.flatten
end

#leaf?Boolean

Returns:

  • (Boolean)


54
55
56
# File 'lib/basic_tree.rb', line 54

def leaf?
  children.empty?
end

#levelObject



46
47
48
# File 'lib/basic_tree.rb', line 46

def level
  path.size
end

#pathObject



22
23
24
# File 'lib/basic_tree.rb', line 22

def path
  ancestors << self
end

#rootObject



42
43
44
# File 'lib/basic_tree.rb', line 42

def root
  path.first
end

#root?Boolean

Returns:

  • (Boolean)


50
51
52
# File 'lib/basic_tree.rb', line 50

def root?
  !parent
end

#siblingsObject



38
39
40
# File 'lib/basic_tree.rb', line 38

def siblings
  root? ? [] : parent.children.select { |child| child != self }
end

#subtreeObject



34
35
36
# File 'lib/basic_tree.rb', line 34

def subtree
  [self] + descendants
end