Can external routes files be included in the main route.rb file?
I have a large number of routes that I would like to split into different route files.
I created "routes-secondary.rb" and added some routes there. Then I tried to add something like this to the main routes of the application. Rb:
requires "# {Rails.root} /config/routes-secondary.rb"
This doesn't work because Rails doesn't recognize routes in routes-secondary.rb. Is there a way to do this right?
source to share
(I updated this answer to use RouteReloader for development)
You can accomplish this easily (even in Rails 4!).
config / routes.rb:
Rails.application.routes.draw do
resources :foo
end
config / routes / included.rb:
Rails.application.routes.draw do
resources :bar
end
config / initializers / routes.rb
Rails.application.routes_reloader.paths.unshift *Dir[File.expand_path("../../routes/**/*.rb", __FILE__)]
This will add all the files in config / routes to the routes of the application, and will probably add them in reverse lexical order by filename. If you want to load the routes in a different order than glob, you can simply push or move routes to route_reloader.paths in the order you want.
rake routes:
Prefix Verb URI Pattern Controller#Action
foo_index GET /foo(.:format) foo#index
POST /foo(.:format) foo#create
new_foo GET /foo/new(.:format) foo#new
edit_foo GET /foo/:id/edit(.:format) foo#edit
foo GET /foo/:id(.:format) foo#show
PATCH /foo/:id(.:format) foo#update
PUT /foo/:id(.:format) foo#update
DELETE /foo/:id(.:format) foo#destroy
bar_index GET /bar(.:format) bar#index
POST /bar(.:format) bar#create
new_bar GET /bar/new(.:format) bar#new
edit_bar GET /bar/:id/edit(.:format) bar#edit
bar GET /bar/:id(.:format) bar#show
PATCH /bar/:id(.:format) bar#update
PUT /bar/:id(.:format) bar#update
DELETE /bar/:id(.:format) bar#destroy
source to share