0

我有一些链接,我从我的 Github API 中提取到我的 Rails 应用程序的视图中。目标是让这些链接最终按文件夹分组(如果它们是嵌套的),并且如果它们没有任何子节点,则它们只是唯一且独立的。

这是我从 Github 存储库中返回的示例:

app
app/assets
app/assets/images
app/assets/images/.keep
app/assets/javascripts
app/assets/javascripts/ace.js
app/assets/javascripts/application.js
app/assets/javascripts/editor.js.coffee
app/assets/stylesheets
app/assets/stylesheets/application.css
app/assets/stylesheets/editor.css.scss
app/controllers
app/controllers/application_controller.rb
app/controllers/concerns

这些链接的http://部分总是相同的,在我看来,我现在只是将它连接起来以使路径成为绝对路径。

如何按文件夹对它们进行分组?我会想象一些字符串方法,但我不确定最好的方法是什么。另外,Ruby 或 JavaScript 是最好的解决方案吗?

4

1 回答 1

2

这是 Ruby 中的一种简单方法,假设您将列表放在一个名为 的数组中paths

grouped = paths.group_by { |p| File.dirname(p) }

这将产生一个包含以下内容的哈希:

{"."=>["app"],
 "app"=>["app/assets", "app/controllers"],
 "app/assets"=>
  ["app/assets/images", "app/assets/javascripts", "app/assets/stylesheets"],
 "app/assets/images"=>["app/assets/images/.keep"],
 "app/assets/javascripts"=>
  ["app/assets/javascripts/ace.js",
   "app/assets/javascripts/application.js",
   "app/assets/javascripts/editor.js.coffee"],
 "app/assets/stylesheets"=>
  ["app/assets/stylesheets/application.css",
   "app/assets/stylesheets/editor.css.scss"],
 "app/controllers"=>
  ["app/controllers/application_controller.rb", "app/controllers/concerns"]}

如果您想摆脱目录元素(例如app/assetsunder app),并且希望值数组包含基本名称而不是完整路径(application.css而不是app/assets/stylesheets/application.css),您可以使用:

grouped.each do |dir, paths|
  # If the path is also a hash key in "grouped", it must be a directory
  paths.delete_if { |path| grouped.has_key? path }
  # Replace each element with its basename
  paths.map! { |path| File.basename(path) }
end

最后,省略空目录:

grouped.delete_if { |dir, paths| paths.empty? }

所有这些都会给你留下:

{"app/assets/images"=>[".keep"],
 "app/assets/javascripts"=>["ace.js", "application.js", "editor.js.coffee"],
 "app/assets/stylesheets"=>["application.css", "editor.css.scss"],
 "app/controllers"=>["application_controller.rb", "concerns"]}
于 2013-11-12T02:04:13.417 回答