DRY Rails Routes
Advance techniques to improve Rails Routing
There could be different ways of writing a block of code but the aim should always be to go for a precise and accurate one. Here in this section, we will be discussing about drying out the routes from Rails to make them more precise in two ways as given below,
- Use of concerns in Rails Routing
- Breaking down routes in different files
So let’s get started straight to the point below,
Use of concerns in Rails Routing
This is one of the very common ways to write down common routes in concern and use it in different places. So let’s create a scenario in which we have to write some routes as below,
resources :clients do
get :followers_list, on: :member
get :common_list, on: :collection
endresources :agents do
get :followers_list, on: :member
get :common_list, on: :collection
end
So, we can reduce the code repetition here using the concern below,
concern :listable do
get :followers_list, on: :member
get :common_list, on: :collection
endresources :clients, concerns: :listableresources :agents, concerns: :listable
And it will give out the same output but this small change will make the code more precise and easy to understand.
Breaking down routes in different files
This may also be a widespread way of using routes for let’s say separation of API-based routes and Web-based routes. So let’s again create a scenario where we have some API-based routes and Web-based routes as below,
# web based routes
resources :users
resources :dashboard, only: :index# api based routes
namespace :api_panel, path: 'api', defaults: { format: :json } do
namespace :v1 do
resources :users
end
end
Since there could be a lot of routes in both of them, we can separate them into multiple files as below,
class ActionDispatch::Routing::Mapper
def draw routes_name
instance_eval(File.read(Rails.root.join("config/routes/#{ routes_name }.rb")))
end
endRails.application.routes.draw do
# Web based Routes
draw :web_based # API based Routes
draw :api_based
end
So now we can create two different files as config/routes/web_based.rb
and config/routes/api_based.rb
to differentiate these routes. Now the fun part to it is we can make concerns to use of common routes by defining draw :concern
before defining Web and API routes and then creating all common routes to the config/routes/concern.rb
, isn’t it amazing? It sure is for me!
Being said so I’ll keep the rest of the experimenting on the reader. See you in the next blog with some new interesting topics.