Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class TreePrinter
- attr_accessor :is_branch
- attr_accessor :get_children
- def initialize
- @arms = Hash.new("| ")
- @arms[""] = ""
- @arms["`"] = " "
- @out = ""
- @is_branch = proc{|node| FileTest.directory?(node) && FileTest.readable?(node) }
- @get_children = proc{|node| node.children(false).sort}
- @format_node = proc{|node| node.to_s}
- end
- def visit(path, leader, tie, arm, node)
- # todo, doesn't quite work for files just yet
- node_str = @format_node.call(node)
- @out << "#{leader}#{arm}#{tie}#{node_str}\n"
- visitChildren(node, leader + @arms[arm])
- @out
- end
- def visitChildren(path, leader)
- return unless @is_branch.call(path)
- kids = @get_children.call(path)
- return if kids.empty?
- arms = Array.new(kids.length - 1, "|") << "`"
- pairs = kids.zip(arms)
- pairs.each { |e| visit(path, leader, "-- ", e[1], e[0]) }
- end
- def format(root)
- visit root, "", "", "", root
- end
- end
Add Comment
Please, Sign In to add comment