ファイルリストをリンク付きでHTMLに書き出す

Indexes設定では都合が悪かったので作成。

#!/usr/bin/ruby -Ku
require 'find'
require 'uri'

def create_filelist_html(root)
  Find.find(root) do |path|
    if File.directory?(path)
      title = path.split('/')[-1]
      open("#{path}/index.html", "w") do |io|
        io.puts '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">'
        io.puts '<html>'
        io.puts '<head>'
        io.puts '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">'
        io.puts "<title>#{title}</title>"
        io.puts '<body>'
        io.puts "<h1>#{title}</h1>"
        io.puts '<hr />'
        io.puts '<ul>'
        Dir.entries(path).sort.each do |file|
          next if /^(index.html|\.|\.\.)$/ =~ file
          f_name = file + (File.directory?("#{path}/#{file}") ? "/" : "")
          io << "<li><a href=\"#{URI.encode("./#{file}")}\">#{f_name}</a></li>\n"
        end
        io.puts '</ul>'
        io.puts '</body>'
        io.puts '</html>'
      end
    end
  end
end

create_filelist_html('/export/files0/')
create_filelist_html('/export/files1/')

日本語ファイル名も取り扱えるようにURI.encodeしてます。ヒアドキュメント使った方がいいのかもしれない。
最初、CGI.encode使っておかしなことになった。以下のような違いがある模様。

URI.escape はURIに使用可能な文字以外をエスケープする
CGI.escape はURLとしての意味を持たせたくない文字をエスケープする

URI.escapeとCGI.escapeの違い - gan2 の Ruby 勉強日記