On this article I’ll focus on a technique for various readability: a easy method to cut up your routes file on a Ruby on Rails undertaking.
Often, after we work on massive Ruby on Rails functions, these include an enormous routes file within the config/routes.rb
.
This may result in a foul developer expertise or a “your file has too many strains” linter warning.
Earlier than leaping into code examples, it’s necessary to notice that the processing order in routes.rb
is prime to backside.
Rails 6.1 introduced again the function that lets you load exterior routes file from the router, because it was eliminated in 2012.
Take a look at your undertaking’s model to verify it’s appropriate with this easy resolution beneath.
Let’s say now we have our undertaking with this construction:
Controllers folder instance
Ideally this undertaking can have namespaced controllers structured in routes like this:
# config/routes.rb
Rails.utility.routes.draw do
root to: "dwelling#index"
devise_for :customers
namespace :api do
# assets
finish
namespace :admin do
# assets
finish
namespace :weblog do
# assets
finish
finish
Conserving a pleasant and helpful rails-way of interpretation, these routes file could be simply cut up utilizing high-level namespaces into different recordsdata.
# config/routes/admin.rb
namespace :admin do
# assets
finish
# config/routes/api.rb
namespace :api do
# assets
finish
# config/routes/weblog.rb
namespace :weblog do
# assets
finish
And eventually:
# config/routes.rb
Rails.utility.routes.draw do
root to: "dwelling#index"
devise_for :customers
draw(:admin) # Will load route file situated in `config/routes/admin.rb`
draw(:api) # Will load route file situated in `config/routes/api.rb`
draw(:weblog) # Will load route file situated in `config/routes/weblog.rb`
finish
Older Rails variations
In case you’re operating your rails undertaking at 2.x model your router in all probability makes use of ActionController::Routing
to attract your routes. At rails 3.0 or greater the router drawer can be outlined by every utility namespaced inside your Software module.
if Rails::VERSION::MAJOR > 2
YourAppName::Software.routes.draw do
...
finish
else
ActionController::Routing::Routes.draw do |map|
...
finish
finish
You need to use this quote in case you’re on a twin boot.
It’s potential your undertaking may want this to load exterior recordsdata:
# utility.rb
config.paths["config/routes"] += Dir[Rails.root.join("config/routes/*.rb")]
Rails docs doesn’t suggest route splitting, until you really want it. It’s as much as your undertaking to resolve how lengthy recordsdata needs to be and the way routes file needs to be listed. Builders can have totally different experiences and totally different factors of view about this, test along with your crew to see what they give thought to this.