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.



25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/giblish/pathtree.rb', line 25

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.



23
24
25
# File 'lib/giblish/pathtree.rb', line 23

def data
  @data
end

#nameObject (readonly)

Returns the value of attribute name.



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

def name
  @name
end

Instance Method Details

#add_path(tail, data = nil) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/giblish/pathtree.rb', line 40

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)


88
89
90
# File 'lib/giblish/pathtree.rb', line 88

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.



72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/giblish/pathtree.rb', line 72

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” }



63
64
65
66
67
68
# File 'lib/giblish/pathtree.rb', line 63

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