Creating a drilldown menu in rails
-
10-06-2021 - |
Question
I have a array of strings which look similar to:
"folder1/filea/x1.png", "folder1/fileb/x2.png", "folder2/folder3/filec/x3.png" .....
And my goal is to create a drilldown menu like: http://iwantaneff.in/repo/plugins/menu-nav/drill.down/index.html
In rails I have tried using the group_by method, but had no luck. essentially I need to create a folder structure like
- folder1
- filea
- x1.png
- fileb
- x2.png
- filea
- folder2
and so on.....
Any idea on where to start? I am having major difficulty approaching this problem. I have used the split method on each array so I get an array of arrays, but this does not seem to be getting anywhere. I think I need to use recursion to go through sub-trees?
Solution
Answer is simple) use recursion for parsing and inserting data
example of parsing =>
def parse(hash)
hash.each do |k,v|
files = v.select{|e| e.size == 1}
hash[k] = {"files" => files.flatten} unless files.empty?
dirs = v - files
unless dirs.empty?
dirs = parse(dirs.group_by{|e| e.shift})
if files.empty?
hash[k] = dirs
else
hash[k].merge! dirs
end
end
end
end
for input
h = {:root => ["folder1/filea/x1.png", "folder1/fileb/x2.png","folder1/fileb/folder4/111", "folder2/folder3/filec/x3.png","folder2/folder3/filec/x4.png"].map{|e| e.split("/")}}
parse(h)
output will be
{:root=>{"folder1"=>{"filea"=>{"files"=>["x1.png"]}, "fileb"=>{"files"=>["x2.png"], "folder4"=>{"files"=>["111"]}}}, "folder2"=>{"folder3"=>{"filec"=>{"files"=>["x3.png", "x4.png"]}}}}}