开发者

Why do I have to delete the index.html file in a rails app to get the controller mapped to the root to display?

开发者 https://www.devze.com 2023-02-01 19:34 出处:网络
I did a quick search, but couldn\'t find a direct answer.New to Rails and just trying to understand why this is the case.I\'d really appreciate it if someone could just point of the piece of code that

I did a quick search, but couldn't find a direct answer. New to Rails and just trying to understand why this is the case. I'd really appreciate it if someone could just point of the piece of code that sho开发者_运维技巧ws where it points to index.html if it exists, or, if that's the wrong way of thinking about it, what the right answer is.


In Rails 3, railties defines a default middleware stack (railties/lib/rails/application.rb) that lets each type of middleware access the request call. The first module in the stack is ActionDispatch::Static (it can be disabled with config.serve_static_assets). The static middleware module is in ActionPack (actionpack/lib/action_dispatch/middleware/static.rb). The relevant lines from that are:

path   = env['PATH_INFO'].chomp('/')
...
if file_exist?(path)
  return @file_server.call(env)

@file_server is defined above as a Rack::File which is in rack/lib/rack/file.rb. It just reads the file and serves the contents as the body.

So when you delete index.html, the file_exist? call fails which just passes the request on to the next middleware and eventually will hit the normal Rails router.


rails will automatically look in the /public folder FIRST before it checks anything. It won't even look at any rb code. This is its way of serving static pages.


Rails is set to look at /public/index.html but that page has some great information on it especially if you are just setting out on your rails journey. As you get into it, you'll learn the first thing you do is rm public/index.html after you create your new empty rails app.


Your quote: "piece of code that shows where it points to index.html if it exists"

I'm not even sure whether your web server even bothers to run a single line of Rails code if it just can pass on a static file. It would be totally inefficient to run Rails code before returning images, static html etc. to the web browser.

I don't know the details of the various Rails implementations there are, but I think a good way to think about it is that the webserver will dispatch a request to Rails only when it doesn't find the (static) file on its filesystem. The request is then passed on to Rails as if it were a File Not found error (without sending the 404 status though)... and then Rails can start to match the URL to its routes file.

0

精彩评论

暂无评论...
验证码 换一张
取 消