Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Divide large routes.rb to multiple files in Rails 5

I want to upgrade my rails 4 app to 5.0.0.beta2. Currently I divided the routes.rb file to multiple files by setting config.paths["config/routes.rb"] e.g.,

module MyApp
  class Application < Rails::Application
    config.paths["config/routes.rb"]
      .concat(Dir[Rails.root.join("config/routes/*.rb")])
  end
end

It seems rails 5.0.0.beta2 also exposes config.paths["config/routes.rb"] but the above code doesn't work. How can I divide routes.rb file in rails 5?

like image 554
Shouichi Avatar asked Feb 24 '16 17:02

Shouichi


1 Answers

Rails 6.1+ built-in way to load routes from multiple files.

From official Rails docs:


Breaking up very large route file into multiple small ones:

If you work in a large application with thousands of routes, a single config/routes.rb file can become cumbersome and hard to read.

Rails offers a way to break a gigantic single routes.rb file into multiple small ones using the draw macro.

# config/routes.rb

Rails.application.routes.draw do
  get 'foo', to: 'foo#bar'

  draw(:admin) # Will load another route file located in `config/routes/admin.rb`
end

# config/routes/admin.rb

namespace :admin do
  resources :comments
end

Calling draw(:admin) inside the Rails.application.routes.draw block itself will try to load a route file that has the same name as the argument given (admin.rb in this case). The file needs to be located inside the config/routes directory or any sub-directory (i.e. config/routes/admin.rb or config/routes/external/admin.rb).

You can use the normal routing DSL inside the admin.rb routing file, however you shouldn't surround it with the Rails.application.routes.draw block like you did in the main config/routes.rb file.


Link to the corresponding PR.

like image 82
Marian13 Avatar answered Oct 17 '22 17:10

Marian13