Ruby 创建递归目录树
I need to recursively traverse a directory and create a tree to be used with the jsTree control. The control accepts a JSON format like so. I need some ruby magic to make this happen cleanly and quickly.
Any help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能想要这样的东西(未经测试):
递归地沿着树走下去,建立一个散列。使用您最喜欢的序列化库将其转换为 json。
You probably want something like this (untested):
Recursively walk down the tree, building up a hash. Turn it into json with your favourite serialisation library.
首先获取你的树,将其转换为叶子的路径列表,类似于:(
不确定上面是否完全遵循你的 jsTree 结构,但原理是相同的。)
这是输入和输出的示例:
然后,对于每个路径,调用
FileUtils#mkdir_p
:你应该没问题。
编辑:更简单的版本:
您不需要创建叶子列表,只需遍历整个树并为每个节点创建一个目录:
Edit2:
哦,对不起,我误解了。因此,这里有一种基于磁盘上的目录树创建哈希的方法:
因此,对于以下结构:
上面的代码返回此哈希:
希望您能设法满足您的需求。
First take your tree, convert it to a list of paths to leaves, similar to:
(Not sure if above exactly follows your jsTree structure, but the principle is the same.)
Here's a sample of input and output:
Then, for each path, call
FileUtils#mkdir_p
:And you should be ok.
Edit: Simpler version:
You don't need to create list of leaves, just traverse whole tree and create a directory for every node:
Edit2:
Oh, sorry, I misunderstood. So, here's a way to make a Hash based on directory tree on disk:
So, for the following structure:
code above returns this hash:
Hope you'll manage to suit it to your needs.
Ruby 的查找模块(
require 'find'
)是极简主义的,但可以很好地处理目录递归:http://www.ruby-doc.org/stdlib/libdoc/find/rdoc/classes/Find.htmlRuby's Find module (
require 'find'
) is minimalist but handles directory recursion well: http://www.ruby-doc.org/stdlib/libdoc/find/rdoc/classes/Find.html截至 2015 年 6 月,接受的答案不起作用。我将密钥
:data
更改为'text'
。我还概括了代码以排除目录和文件。The accepted answer did not work as of June 2015. I changed the key
:data
to'text'
. I also generalized the code to exclude directories and files.