Generate static pages in Rails

I wanted a nice looking 404, 500 and maintenance pages for my Rails app and I couldn’t serve them from Rails.

My requirements were:

  • I didn’t want to hand code the pages – I’m using a web framework for a reason!
  • I wanted to use the application’s layout
  • I needed that pages to be static so I could serve them when the Rails app was either down or when it had ‘issues’

My solution was to:

  1. create a controller for the purpose of rendering the static pages
  2. tailor your views so you have nice 404, 500 and maintenance pages
  3. modify the layout so that signin and register were not longer present
  4. create a rake task to render the pages and write them out to a file

Items 1 & 2 are just standard Rails stuff – so go nutz young coders.

Item 3 was pretty straight forward, in the layout I put:

  <% unless controller.controller_name == "errors" %>
     put your sign-in code here
  <% end %>

Item 4 was a bit trickier, but this rake task should get you up and running.

  namespace :generate do
    task :pages => :environment do
      require 'action_controller/integration'
      app = ActionController::Integration::Session.new
      app.host! "stateofflux.com"
      [['/errors/error_404', 'public/40 4.html'],
       ['/errors/error_500', 'public/500.html']].each do |url, file|
        begin
          app.get url
          File.open(file, "w") { |f| f.write app.response.body }
        rescue Exception => e
          puts "Could not write file #{e}"
        end
      end
    end
  end

We run the rake task in the development environment then check it in, but you could run it in production if there was production data that you needed to create the page.

  1. James Knight says:

    This worked a treat for me – I’ve been under huge time pressure to knock out a static site, and am using Rails to break it into includes. I needed something to generate the static files at the end, and this example has galvanised me into creating my first rake task.

    thanks!

  2. James Knight says:

    FWIW, I also cannibalised this (http://snippets.dzone.com/posts/show/4792) to grab the full list of actions each time, so that I don’t have to update the task when I add new controllers/actions.

  1. There are no trackbacks for this post yet.

Leave a Reply