I've manage that this way:
# config/application.rb
config.autoload_paths << Rails.root.join('config/routes')
# config/routes.rb
Rails.application.routes.draw do
root to: 'home#index'
extend ApiRoutes
end
# 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
Here I added config/routes
directory to autoload modules defined in it.
This will ensure that routes are reloaded when these files change.
Use extend
to include these modules into the main file (they will be autoloaded, no need to require them).
Use instance_exec
inside self.extended
to draw routes in the context of router.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…