Ruby创建递归目录树 [英] Ruby Create Recursive Directory Tree

查看:276
本文介绍了Ruby创建递归目录树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要递归地遍历一个目录,并创建一个要与 jsTree 控件一起使用的树。该控件接受JSON格式如此。我需要一些红宝石魔法才能使这个发生得很干净,快速。

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.

任何帮助都不胜感激。

推荐答案

你可能想要这样的东西(未经测试):

You probably want something like this (untested):

def directory_hash(path, name=nil)
  data = {:data => (name || path)}
  data[:children] = children = []
  Dir.foreach(path) do |entry|
    next if (entry == '..' || entry == '.')
    full_path = File.join(path, entry)
    if File.directory?(full_path)
      children << directory_hash(full_path, entry)
    else
      children << entry
    end
  end
  return data
end

递归地走下树,建立哈希。把它变成json与你最喜欢的序列化库。

Recursively walk down the tree, building up a hash. Turn it into json with your favourite serialisation library.

这篇关于Ruby创建递归目录树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆