Class: PathTree

Inherits:
Object
  • Object
show all
Defined in:
lib/giblish/pathtree.rb

Overview

This class can convert the following paths: basedir/file_1 basedir/file_2 basedir/dir1/file_3 basedir/dir1/file_4 basedir2/dir2/dir3/file_5

into the following tree: basedir

file_1
file_2
dir1
  file_3
  file_4

basedir2

dir2
  dir3
    file_5

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tail = nil, data = nil) ⇒ PathTree

Returns a new instance of PathTree.


22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/giblish/pathtree.rb', line 22

def initialize(tail = nil, data = nil)
  @children = []
  @it = nil
  @name = nil
  return unless tail

  tail = tail.split("/") unless tail.is_a?(Array)
  @name = tail.shift
  if tail.length.positive?
    @children << PathTree.new(tail, data)
  else
    @data = data
  end
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.


20
21
22
# File 'lib/giblish/pathtree.rb', line 20

def data
  @data
end

#nameObject (readonly)

Returns the value of attribute name.


20
21
22
# File 'lib/giblish/pathtree.rb', line 20

def name
  @name
end

Instance Method Details

#add_path(tail, data = nil) ⇒ Object


37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/giblish/pathtree.rb', line 37

def add_path(tail, data = nil)
  tail = tail.split("/") unless tail.is_a?(Array)
  return if tail.empty?

  ch = get_child tail[0]
  if ch
    tail.shift
    ch.add_path tail, data
  else
    @children << PathTree.new(tail, data)
  end
end

#leaf?Boolean

Public: is this node a leaf

Returns: true if the node is a leaf, false otherwise

Returns:

  • (Boolean)

85
86
87
# File 'lib/giblish/pathtree.rb', line 85

def leaf?
  @children.length.zero?
end

#sort_childrenObject

Public: Sort the nodes on each level in the tree in lexical order but put leafs before non-leafs.


69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/giblish/pathtree.rb', line 69

def sort_children
  @children.sort! do |a, b|
    if (a.leaf? && b.leaf?) || (!a.leaf? && !b.leaf?)
      a.name <=> b.name
    elsif a.leaf? && !b.leaf?
      -1
    else
      1
    end
  end
  @children.each(&:sort_children)
end

#traverse_top_down(level = 0, &block) ⇒ Object

Public: Visits each node by following each branch down from the

root, one at the time.

level - the number of hops from the root node block - the user supplied block that is executed for every visited node

the level and node are given as block parameters

Examples Print the name of each node together with the level of the node traverse_top_down{ |level, n| puts “#level #PathTree.nn.name” }


60
61
62
63
64
65
# File 'lib/giblish/pathtree.rb', line 60

def traverse_top_down(level = 0, &block)
  @children.each do |c|
    yield(level, c)
    c.traverse_top_down(level + 1, &block)
  end
end