将大 routes.rb 分成 Rails 中的多个文件 5

Divide large routes.rb to multiple files in Rails 5

我想将我的 rails 4 应用程序升级到 5.0.0.beta2。目前我通过设置 config.paths["config/routes.rb"]routes.rb 文件分成多个文件,例如

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

似乎 rails 5.0.0.beta2 也公开了 config.paths["config/routes.rb"] 但上面的代码不起作用。如何在 rails 5 中划分 routes.rb 文件?

你可以在config/application.rb中写一些代码

config.paths['config/routes.rb'] = Dir[Rails.root.join('config/routes/*.rb')]

Here's a nice article, simple, concise, straight to the point - 不是我的。

config/application.rb

module YourProject
  class Application < Rails::Application
    config.autoload_paths += %W(#{config.root}/config/routes)
  end
end

config/routes/admin_routes.rb

module AdminRoutes
  def self.extended(router)
    router.instance_exec do
      namespace :admin do
        resources :articles
        root to: "dashboard#index"
      end
    end
  end
end

config/routes.rb

  Rails.application.routes.draw do
    extend AdminRoutes

    # A lot of routes
  end

我喜欢this gist and expanded on in this blog post中展示的方法:

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

BCX::Application.routes.draw do
  draw :api
  draw :account
  draw :session
  draw :people_and_groups
  draw :projects
  draw :calendars
  draw :legacy_slugs
  draw :ensembles_and_buckets
  draw :globals
  draw :monitoring
  draw :mail_attachments
  draw :message_preview
  draw :misc

  root to: 'projects#index'
end

Rails 6.1+ built-in 从多个文件加载路由的方法。

From official Rails docs:


将非常大的路由文件分成多个小文件:

如果您在具有数千条路由的大型应用程序中工作,单个 config/routes.rb 文件可能会变得笨重且难以阅读。

Rails 提供了一种使用绘图宏将巨大的单个 routes.rb 文件分解为多个小文件的方法。

# 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

Rails.application.routes.draw 块本身内调用 draw(:admin) 将尝试加载与给定参数同名的路由文件(在本例中为 admin.rb)。该文件需要位于 config/routes 目录或任何 sub-directory(即 config/routes/admin.rbconfig/routes/external/admin.rb)内。

您可以在 admin.rb 路由文件中使用普通路由 DSL,但是您不应该像在主 config/routes.rb 文件中那样用 Rails.application.routes.draw 块将其包围。


Link to the corresponding PR.