rails 4: split routes.rb into multiple smaller files

This was removed from Rails 4 in June of 2012. 5e7d6bba reverts an earlier commit, removing support for loading multiple external route files as part of config.rb.

For further read, check out the comments on this commit.


A bit late to the party but you can do this in Rails 4 by monkey patching the mapper at the top of your routes.rb file. ie:

# config/routes.rb
class ActionDispatch::Routing::Mapper
  def draw(routes_name)
    instance_eval(File.read(Rails.root.join("config/routes/#{routes_name}.rb")))
  end
end

And then using the draw method in routes.rb with:

Rails.application.routes.draw do
  draw :api
end

This will expect a file in config/routes/api.rb.

A slightly fuller explanation with examples of splitting the routes file here.


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.