Cowell Computer Consulting

Static Pages in Rails

I just read an interesting post on how to handle static pages in rails and I had a different approach that I wanted to share. There's lots of different ways to do this and each method has its own merit.

When I say static page, I mean any page that doesn't fit into your other controllers. This might be an about us or a contact page or anything else that might not require a dedicated controller to handle.

In routes.rb, I would set something like this up:

map.static '/static/:id', :controller => "static", :action => "show"

We can grab the name of the page from params[:id] in the controller. Feel free to change the name 'id' some something else if it gives you that wrong feeling to treat something as an id that isn't really an id.

Next, I define a controller called static.


class StaticController < ApplicationController
  def show
     short_name = params[:id]
     begin
       render short_name
     rescue ActionView::MissingPageTemplate
       render :file => "#{RAILS_ROOT}/public/404.html", :status => 404
     end
   end
end

So, what's happening here? We know we have an params[:id] or the route wouldn't match. We then call a begin block, so that we can rescue the exception. Which, in our case, is if someone passes an invalid filename through or the page hasn't yet been defined under app/views/static/pagename.html.erb. We just handle it as a 404.

What about if we want our static pages to live in a namespace without /static at the beginning ? ie. /about instead of /static/about

Define a regular expression that matches all the pages you want to support.

STATIC_PAGES = %w(about contact fun_facts)
STATIC_REGEXP = %r{#{STATIC_PAGES.join("|")}}

Then, in your routes file use the requirements parameter to match only these pages.

map.static ':id', :controller => "static", :action => "show", :requirements => {:id => STATIC_REGEXP}

This is just another approach and there are lots of ways to do this. I was inspired by Yehuda Katz to write this as he recently wrote a post about giving back to the community. Also, be sure to check out his posts about rails 3.

Posted by Luke Cowell on February 11, 2010 at 09:22 AM