Guest User

Untitled

a guest
Jan 24th, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. class TreePrinter
  2. attr_accessor :is_branch
  3. attr_accessor :get_children
  4.  
  5. def initialize
  6. @arms = Hash.new("| ")
  7. @arms[""] = ""
  8. @arms["`"] = " "
  9. @out = ""
  10. @is_branch = proc{|node| FileTest.directory?(node) && FileTest.readable?(node) }
  11. @get_children = proc{|node| node.children(false).sort}
  12. @format_node = proc{|node| node.to_s}
  13. end
  14.  
  15. def visit(path, leader, tie, arm, node)
  16. # todo, doesn't quite work for files just yet
  17. node_str = @format_node.call(node)
  18. @out << "#{leader}#{arm}#{tie}#{node_str}\n"
  19. visitChildren(node, leader + @arms[arm])
  20. @out
  21. end
  22.  
  23. def visitChildren(path, leader)
  24. return unless @is_branch.call(path)
  25. kids = @get_children.call(path)
  26. return if kids.empty?
  27. arms = Array.new(kids.length - 1, "|") << "`"
  28. pairs = kids.zip(arms)
  29. pairs.each { |e| visit(path, leader, "-- ", e[1], e[0]) }
  30. end
  31.  
  32. def format(root)
  33. visit root, "", "", "", root
  34. end
  35. end
Add Comment
Please, Sign In to add comment