LoginSignup
3
1

More than 3 years have passed since last update.

WebricのFancyIndexingにスタイルシートをあてる

Posted at

頑張ってあてます。ApacheでいうIndexStyleSheetです。

IndexStyleSheet ディレクティブ
http://httpd.apache.org/docs/2.2/ja/mod/mod_autoindex.html#indexstylesheet

Webricの起動時にDocumentRootオプションを渡してやると、ファイルのリストアップが自動的に表示されます。FancyIndexingと言うそうです。

require "webrick"

server = WEBrick::HTTPServer.new({
  DocumentRoot: '.'
})

server.start

しかしながらWebricには、IndexStyleSheetのようなオプションはありません。
ソースコードをみてみると、set_dir_listと言うメソッドの中でHTMLを生成して返却しているようです。

無理やり上書きします。

require "webrick"

server = WEBrick::HTTPServer.new

server.mount_proc('/') do |req, res|
  handler = WEBrick::HTTPServlet::FileHandler.new(server, Dir.pwd, {
    :FancyIndexing => true,
    :IndexStyleSheet => "/style.css",
  })

  original = handler.method(:set_dir_list)
  handler.define_singleton_method(:set_dir_list) do |req, res|
    original.call(req, res)
    if @options[:IndexStyleSheet]
      res.body.gsub!("</style>", "</style><link rel=\"stylesheet\" href=\"#{@options[:IndexStyleSheet]}\">")
    end
  end

  handler.service(req, res)
end

server.start
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1