Ben Doesn't Read (was: "Cherish Your Routes") October 11th, 2007

Check out the new punchline to this article!

There is no correlation to your application URLs and the location of files in your Rails app. For example, you can take a request for "/losangeles.html" and run the "SouthernCalifornia#index" action. This flexibility comes from Rails' "Routing."

When you hit a URL in Rails, the URL gets run through a series of regular expressions to figure out the action. You define those regexes in your routes.

For performance (and maintainability), keep your routes lean. Here's some low hanging fruit:

map.with_options(:controller => 'about') do |about_map|
  about_map.connect 'about', :action => 'about'
  about_map.connect 'about/:action'
end
map.about 'about/:action', :controller => 'about', :action => 'about'

Plus, we avoid using with_options.

Of course you should test your routes before refactoring. Here's a helper:

def assert_route(url, parameters)
    result = ActionController::Routing::Routes.recognize_path(url)
    parameters.each do |k,v|
      assert_equal v, result[k], "Route recognition fails for #{url}: #{result[k]} => #{v}"
    end
  end

And the test:

def test_should_recognize_about_routes
  assert_route '/about', :controller => 'about', :action => 'about'
  assert_route '/about/madeupaction', :controller => 'about', :action => 'madeupaction'
end

The New Ending

Turns out, I just recreated assert_generates