1
def self.directory_hash(path, name=nil)
    data = {:parent => (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を返す上記のメソッドを使用しました:-

{:parent=>"public", :children=>["422.html", {:parent=>"applications", :children=>[{:parent=>"1", :children=>[{:parent=>"1", :children=>[{:parent=>"1", :children=>["configurations.xml"]}, {:parent=>"2", :children=>["configurations.xml"]}, "Projects.rar"]}, {:parent=>"2", :children=>[{:parent=>"9", :children=>["configurations.xml"]}, "rest.rar", {:parent=>"5", :children=>["configurations.xml"]}, {:parent=>"6", :children=>["configurations.xml"]}, {:parent=>"3", :children=>["configurations.xml"]}, {:parent=>"4", :children=>["configurations.xml"]}]}]}, {:parent=>"2", :children=>[{:parent=>"3", :children=>["Projects.rar"]}, {:parent=>"4", :children=>["rest.rar"]}]}]}, "500.html", "robots.txt", "favicon.ico", {:parent=>"data", :children=>[]}, "_index.html", "404.html"]}

私のビューでは、上記の出力から構造を表示したいので、ビューは次のようになります。

public
 422.html
 applications
  1
   1
    1
    2
  2
.....
.....
.....

そうオン

このjsonを保持する変数があります

@structure = ApplicationVersion.directory_hash("public")

では、ツリーを構築できるように、上記のjsonを読み取るためにどのコードを記述する必要がありますか?

4

1 に答える 1

1

試す:

your_hash = {:parent=>"public", :children=>["422.html", {:parent=>"applications", :children=>[{:parent=>"1", :children=>[{:parent=>"1", :children=>[{:parent=>"1", :children=>["configurations.xml"]}, {:parent=>"2", :children=>["configurations.xml"]}, "Projects.rar"]}, {:parent=>"2", :children=>[{:parent=>"9", :children=>["configurations.xml"]}, "rest.rar", {:parent=>"5", :children=>["configurations.xml"]}, {:parent=>"6", :children=>["configurations.xml"]}, {:parent=>"3", :children=>["configurations.xml"]}, {:parent=>"4", :children=>["configurations.xml"]}]}]}, {:parent=>"2", :children=>[{:parent=>"3", :children=>["Projects.rar"]}, {:parent=>"4", :children=>["rest.rar"]}]}]}, "500.html", "robots.txt", "favicon.ico", {:parent=>"data", :children=>[]}, "_index.html", "404.html"]}  

new_hash= your_hash.to_s.gsub(/(\[\"\S*\"\])/,'').gsub(/(\[|\]|\{|\})/,'').gsub('=>',',').gsub(',,',',')

new_hash.split(',').each {|i| puts i if i.strip[0] != ":"}
于 2013-03-01T12:39:12.420 に答える