使用机架静态页面编写404错误页面路由

时间:2012-12-08 10:08:15

标签: ruby-on-rails ruby heroku rack middleware

如何在config.ru文件中映射404错误页面?机架静态页面(在heroku上托管)?

到目前为止,我在我的config.ru文件中有这个

use Rack::Static, 
  :urls => ["/css", "/images", "/fonts", "/js", "/robots.txt"],
  :root => "public"

run lambda { |env|
  [
    200, 
    {
      'Content-Type'  => 'text/html', 
      'Cache-Control' => 'public, max-age=86400' 
    },
    File.open('public/index.html', File::RDONLY)
  ]
}

我正在尝试做这样的事情:

if env["PATH_INFO"] =~ /^\/poller/
  [200, {"Content-Type" => "text/html"}, ["Hello, World!"]]
else
  [404, {"Content-Type" => "text/html"}, ["Not Found"]]
end

如何使用Rack实现这一目标?请分享您可以使用的任何链接,以便在Rack上了解更多高级内容。我没有真正发现宝石的基本链接有用。

1 个答案:

答案 0 :(得分:3)

您应该使用Rack::Builder,它会自动为未映射的网址抛出404:

app = Rack::Builder.new do

  map '/poller' do

    use Rack::Static,
      :urls => ["/css", "/images", "/fonts", "/js", "/robots.txt"],
      :root => "public"

    run lambda { |env|
      [
        200, 
        {
          'Content-Type'  => 'text/html', 
          'Cache-Control' => 'public, max-age=86400' 
        },
        File.open('public/index.html', File::RDONLY)
      ]
    }
  end

end.to_app

run app