Routing Concerns [Rails 4 Countdown to 2013]

Posted on

This post is part of a series of 31 Rails 4 articles being released each day in December 2012.

The Rails config/routes.rb file encapsulates all the mappings from URLs to controller actions. Over the years, helpful additions have been added to slim this file down so that as developers, we can stop repeating ourselves. One example of this was the routing method resources, which maps four named routes to seven controller actions based on the HTTP request method.

As of Rails 4, routing concerns have been added to the router. Routing concerns allows you to declare common routes, which can be mixed into other resources and routes.

Example

A common example of duplication in the config/routes.rb file happens when a polymorphic association is nested under a parent resource.

Here is an example of many resources which also have comments:

The Rails 3 Way

Older::Application.routes.draw do
  resources :projects do
    resources :comments
  end

  resources :tasks do
    resources :comments
  end

  resources :articles do
    resources :comments
  end
end

The Rails 4 Way

Using the routing method concern, we can now define common routes. All routes within a concern will not be included in your routes by default. The concern routes will only be included within a resource by passing it to the routing option :concerns. The :concerns option can accept one or more concerns.

Newer::Application.routes.draw do
  concern :commentable do
    resources :comments
  end

  resources :projects, concerns: :commentable
  resources :tasks, concerns: :commentable
  resources :articles, concerns: :commentable
end

Upgrade Path

If this is something you want to try in your Rails 3.2 application today, you can use a proof of concept gem named routing_concerns at your own risk. The code has since been merged into the Rails codebase.

Further Reading

002

This post is by Kevin Faustino. Kevin is the Chief Craftsman of Remarkable Labs and also the founder of the Toronto Ruby Brigade.


Comments

comments powered by Disqus