I've wanted to have a list of files to display on one a page in my Rails app, with stacked ULs that recurse through "public/filer", and all it's subdirectories, showing links to the actual files for download.
After a while of googling and experimenting, this helper is what I came up with, it can easily be called from a view with
1 <%= raw list %>
. You can see this snippet in action here.
1 def list(path = "#{RAILS_ROOT}/public/filer" ) 2 html ="" 3 glob = Dir.glob("#{path}/*").sort! 4 for i in glob 5 html << "<li>#{File.basename(i)} <ul>#{list i}</ul></li>" if File.directory?(i) 6 end 7 for i in glob 8 html << "<li>#{ link_to File.basename(i), relativepath(i) } </li>" if File.file?(i) 9 end 10 html 11 end 12 13 def relativepath(abspath) 14 path = abspath.split(File::SEPARATOR) 15 rel = "#{RAILS_ROOT}/public".split(File::SEPARATOR) 16 while path.first == rel.first 17 path.shift 18 rel.shift 19 end 20 file = "/#{path.join(File::SEPARATOR)}" 21 end
The two seperate "for" loops are necessary to get the directories to display before the files. While this can be solved by other, probably more elegant ways, this seemed to be the quickest and easiest solution.
2011.02.22