Fork me on GitHub
Hoopla! - now with extra whiz-bang home

I launched JCFootballProspects.com a while ago and things have been going smoothly but the site is stuck with the nasty black-on-white error messages when somebody types in a wrong address.

I'm now at the point where I want to give out some fancy 404 pages and I've been looking around at what other folks have done. I'm amazed to find that all the examples I can find have a 404.html page in the #{RAILS_ROOT}/public directory. I'm sure it's effective to just have a plain-html file that gets served up for errors (and it's certainly a lot better than the default ugly stuff) but I'm convinced there are advantages to having application-provided 404 pages as well.

There are three different kinds of errors I trap and respond to: A user gives incorrect or insufficient parameters to a page view A user attempts to access an action that doesn't exist * A user attempts to access a controller that doesn't exist

The first is easily handled - even the AWDWR book shows in an early example that you can output a flash message if something goes wrong with a request. The second is only slightly more complicated but, luckily, Ruby has a great way to respond to missing actions on controllers using method_missing. The solution to the third is provided by Rails' routing capabilities.

How to hook up an app-driven 404 page:

The first thing I did was added a view to my default controller (mine is called 'home'). I created ./app/views/home/404.rhtml and put just some basic stuff in it:


<%= content_tag 'h2', 'Whoops!' %>

<%= content_tag 'h3', 'Page not found' %>

[insert message here]

The next step was to add method_missing to my application controller: <typo:code lang="ruby">

class ApplicationController < ActionController::Base

...

def method_missing(methodname, *args) @methodname = methodname @args = args render 'home/404', :status => 404 end

end

And one super low priority route (put it at the very bottom) finishes off the job:


  map.error ':controllername',  :controller => 'home',

                          :action => '404'

blog comments powered by Disqus