class PathTree
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
Attributes
data[R]
name[R]
Public Class Methods
new(tail = nil, data = nil)
click to toggle source
# 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
Public Instance Methods
add_path(tail, data = nil)
click to toggle source
# 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?()
click to toggle source
Public: is this node a leaf
Returns: true if the node is a leaf, false otherwise
# File lib/giblish/pathtree.rb, line 85 def leaf? @children.length.zero? end
sort_children()
click to toggle source
Public: Sort the nodes on each level in the tree in lexical order but put leafs before non-leafs.
# 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) { |level, c| ... }
click to toggle source
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} #{n.name}” }
# 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
Private Instance Methods
get_child(segment_name)
click to toggle source
# File lib/giblish/pathtree.rb, line 91 def get_child(segment_name) ch = @children.select { |c| c.name == segment_name } ch.length.zero? ? nil : ch[0] end