Skip to content

Instantly share code, notes, and snippets.

@klyonrad klyonrad/dir_dirtree.rb
Last active Aug 29, 2015

Embed
What would you like to do?
ruby print_dirtree_style
# license: MIT
require 'to_latex'
module Indoctrinatr
module Tools
class DirectoryHelpers
def initialize
@dirtree_lines = []
end
# recursive:
# modified from http://compsci.ca/v3/viewtopic.php?t=13034
def print_dirtree_style dir = '.', nesting = 2 # nesting starts with 2, because for \dirtree 1 is root
Dir.foreach(dir) do |entry|
next if entry =~ /^\.{1,2}/ # Ignore ".", "..", or hidden files
@dirtree_lines.push ".#{nesting} #{entry}. ".to_latex # formatting for \dirtree: .<level><space><text-node>.<space>
if File.stat(d = "#{dir}#{File::SEPARATOR}#{entry}").directory?
print_dirtree_style(d, nesting + 1)
end
end
@dirtree_lines
end
# iterative:
def print_dirtree_style directory = '.'
Dir.glob("#{directory}/**/*").inject [] do |entries, entry| # list entries recursively
nesting = entry.count(File::SEPARATOR) + 1 # nesting starts with 2, because for \dirtree 1 is root
name = entry.split(File::SEPARATOR).last
entries.push ".#{nesting} #{name}. " # formatting for \dirtree: .<level><space><text-node>.<space>
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.