Split Ruby on Rails routes into multiple smaller files
One time I faced fact that my application is big enough and routes.rb look like a mess. I’ve managed that this way.
I added routes directory to application config directory and added it in autoload_paths to ensure that routes are reloaded when these files change.
# config/application.rb
config.autoload_paths << Rails.root.join('config/routes')
Then moved necessary routes to small files like this.
# config/routes/api_routes.rb
module ApiRoutes
def self.extended(router)
router.instance_exec do
namespace :api do
resources :tasks, only: [:index, :show]
end
end
end
end
Use instance_exec inside self.extended to draw routes in the context of router.
After I refactor routes.rb like this.
# config/routes.rb
Rails.application.routes.draw do
root to: 'home#index'
extend ApiRoutes
end
*Use extend to include these modules into the main routes.rb (they will be autoloaded, no need to require them).*