codykrieger
codykrieger

Reputation: 1780

Rails static page routing - is there a better way?

To clarify, here's the situation:

I'm building a really simple CMS that will become the base for several apps I have plans to create in the future. I'd really like to be able to create a page called "About" (which will be mostly static) and automatically be able to access it at "/about", without having to modify routes.rb.

I currently have a wildcard route like this, which works just fine:

match '/*slug', :to => 'pages#dynamic_page', 
                :constraints => { :fullpath => /.+\.html/ }

The issue is, I'd really like to be able to omit the ".html" at the end. However, I prefer the extension over a url like "/pages/about". Is there a better way to handle this? The issue that occurs when I remove the constraint is that requests to items that don't exist go through the Rails router, which is obviously less than desirable, as that's extra overhead that has to be handled.

Is there a better way? Is there some way to avoid the router entirely if the page being requested is a static page, so I can eliminate the wildcard route?

Thanks!

Upvotes: 3

Views: 2764

Answers (1)

David Demaree
David Demaree

Reputation: 385

To solve this in the Rails router, tou should be able to just add a route to the very bottom of routes.rb that looks something like this:

match '/:slug(.:format)', :to => 'pages#dynamic_page'

The parentheses mark the :format parameter of the route as optional, so /about or /about.html should work.

This needs to be at the bottom of the routes file, so that it won't interfere with your other routes.

If you want to avoid the Rails router, you have two options, both a little more advanced.

  1. In your web server's config, add a rewrite rule that maps /about to some other URI.

  2. Add a Rack middleware or Rails metal to handle your static page routes. This avoids running these requests through the whole Rails routing stack, but the Rails 3 router is pretty fast and I'm not sure it's worth it to add this much complexity just to serve a semi-static page.

You may also wanna look into the High Voltage gem. It's a Rails engine for serving up mostly static pages. By default it gives you a /pages/about style URL, but you could then add the following to your routes to make it prettier:

# High Voltage treats pages like a REST resource; the page's name is the ID 
match '/:id(.:format)', :to => 'high_voltage/pages#show'

Upvotes: 2

Related Questions