Skip to content

Instantly share code, notes, and snippets.

@DougEverly
Created June 27, 2019 19:35
Show Gist options
  • Select an option

  • Save DougEverly/58e4ae70da63fc4238fcc5a5cd0c3c88 to your computer and use it in GitHub Desktop.

Select an option

Save DougEverly/58e4ae70da63fc4238fcc5a5cd0c3c88 to your computer and use it in GitHub Desktop.
Creates a directory structure of nested components loaded from a TSV file.
require "file_utils"
ROOT_PATH = Path.home / Path.new("Documents/Layout")
class Layout
getter parentId : Int32?
getter container : Bool
property children : Array(Layout)
def initialize(@id : Int32, @parentId : Int32?, @name : String, @type : String, @container : Bool)
@children = Array(Layout).new
end
def unique_name : String
"%00d-%s" % [@id, @name]
end
def tree
visit_children(Array(String).new)
end
def visit_children(apath : Array(String))
path = apath.dup
path << unique_name
begin
if container || !children.empty?
FileUtils.mkdir_p((ROOT_PATH / Path.new(path)).to_s)
else
FileUtils.touch((ROOT_PATH / Path.new(path)).to_s)
end
end
children.each do |child|
child.visit_children(path)
end
end
end
layouts = Hash(Int32, Layout).new
file_path = Path.home / Path["Desktop/layout.tsv"]
# load all nodes
File.each_line(file_path) do |line|
puts line
id, parent, name, type, container = line.split("\t")
layouts[id.to_i] = Layout.new(id.to_i, parent.to_i?, name, type, (container == "true"))
end
# relate
roots = Array(Layout).new
layouts.each do |id, layout|
if parentId = layout.parentId
parent = layouts[layout.parentId]
parent.children << layout
else
roots << layout
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment