caikesouza

Rails 4 Routing Concerns

One of the new features in the upcoming Rails 4 release is called routing concerns. This feature helps reduce code duplication on your routes file by allowing you to declare common routes that can be reused inside other resources and routes.

image

Take the following set of routes, for example:

resources :messages do
  resources :comments
  resources :categories
  resources :tags
end
 
resources :posts do
  resources :comments
  resources :categories
  resources :tags
end
 
resources :items do
  resources :comments
  resources :categories
  resources :tags
end

Notice the duplication every time we want to state that a resource can have comments, categories and tags. Let’s extract these into a concern called sociable:

concern :sociable do
  resources :comments
  resources :categories
  resources :tags
end

We can now use the sociable concern to reference these set of resources:

resources :messages, concerns: :sociable
resources :posts, concerns: :sociable
resources :items, concerns: :sociable

Concern blocks can also take an options argument, which is passed down to the resources, like so:

concern :sociable do |options|
  resources :comments, options
  resources :categories, options
  resources :tags, options
end

resources :posts do
  concerns :sociable, only: :create
end

Routing concerns is a feature that helps keep our routes clean and easy to maintain. It will be part of Rails 4, but if you wish to use this feature in your Rails 3.2 applications, you can do so via the routing_concerns gem

- Caike Souza

(source: http://www.flickr.com/photos/teacherafael/886753421)

02.14.13 ← See All Posts
blog comments powered by Disqus