Even though Rails 2.2 is officially in "release candidate" status, new features are still making their way into the source code tree. While we could debate the suitability of this from a release engineering point of view, some of the new features are certainly sweet. The latest is the addition of the :only and :except options to RESTful routes.

Normally, using map.resources creates routes for all seven of the default actions (index, show, new, create, edit, update, and destroy) for the resource. But in Rails 2.2 (or in the current edge builds), you can fine-tune this behavior. The :only option specifies that only certain routes should be generated:

[sourcecode language='ruby']
map.resources :customers, :only => [:index, :show, :destroy]
[/sourcecode]

As with most places in Rails, you can use :except as the opposite of :only:

[sourcecode language='ruby']
map.resources :customers, :except => :index
[/sourcecode]

That declaration would give you six of the seven default routes, omitting only a route for the index action.

In addition to an action or an array of actions, you can also supply the special symbols :all or :none to the :only and :except options.

Why do this? In addition to making your code easier to follow, the smaller you can make the routing table, the less memory it will take up - and the less processing time route recognition and generation will take. It can also lower the attack surface of your application by removing unused routes, which is a security win.