Generate static pages in Rails
Posted on July 14th, 2008 @ 09:05 PM by mark
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’
- create a controller for the purpose of rendering the static pages
- tailor your views so you have nice 404, 500 and maintenance pages
- modify the layout so that signin and register were not longer present
- 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:1 2 3 |
<% 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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.
404, 500, apache, errorpages, layout, nginx, rails, rake, static