The Power of method_missing

Ruby’s method_missing (which essentially provides a rescue hook for any calls to methods that are missing - not defined) comes in pretty handy with Rails. (Now, I’m no Ruby on Rails guru, so take the following with a grain of salt, but I found it pretty effective.

Every URL maps to a controller then a view (after your URL, it’s /controller/view). What if a user tries to go to a view that’s not there? Say you have a controller called “foo” that has a view mapped to “bar.” /foo/bar works just fine. But if a user types in /foo/baz, you’re in a little bit of trouble. Here’s where method missing comes in: in your application.rb file, just add a declaration for method_missing and have method_missing take care of things for you by redirecting or otherwise re-routing that bad request. Here’s an example:

def method_missing(url)
  redirect_to :controller => "foo", :action => "bar"
end

Any errant method calls (read: any attempts to visit a controller action that doesn’t exist) is now safely handled: you’ve essentially intercepted that phony URL in application.rb and handled it as gracefully as possible. You can redirect, render a special template, or anything else you’d like. A really, really neat trick!

technorati tags:, , , ,

Comments are closed.

I'm Reading…
Search This Site

AddThis Feed Button

Need great hosting?

Categories