【问题标题】:Divide large routes.rb to multiple files in Rails 5在 Rails 5 中将大 routes.rb 划分为多个文件
【发布时间】:2016-06-07 03:36:49
【问题描述】:

我想将我的 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 文件?

【问题讨论】:

标签: ruby-on-rails-5


【解决方案1】:

Rails 6.1+ 内置方式从多个文件加载路由。

From official Rails docs:


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

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

Rails 提供了一种方法,可以使用 draw 宏将一个巨大的单个 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 目录或任何子目录(即config/routes/admin.rbconfig/routes/external/admin.rb)内。

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


Link to the corresponding PR.

【讨论】:

  • 酷,我会在6.1之后迁移到官方的方式。谢谢!
【解决方案2】:

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

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

【讨论】:

  • 非常感谢。此解决方案还会在代码更改时自动重新加载路由。这里有更多信息:makandracards.com/makandra/… 请注意,如果在您的原始路由中,您的代码在范围内,那么您的新路由文件也需要具有该范围
  • 当您定义了关注点并将它们从一个路由文件引用到另一个文件时,此解决方案似乎不起作用。
【解决方案3】:

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

【讨论】:

  • 是否可以使用此解决方案,并且在更改路线文件时rails会自动重新加载?
  • Rails 似乎为这种看起来更容易的案例提供了一种官方方式。 edgeguides.rubyonrails.org/…
【解决方案4】:

我喜欢this gist 中演示并在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

【讨论】:

  • 我们已经使用了很长一段时间,但不幸的是它不会自动重新加载路由,您必须启动/停止服务器
猜你喜欢
  • 2013-09-21
  • 1970-01-01
  • 2013-11-15
  • 1970-01-01
  • 1970-01-01
  • 2017-05-14
  • 2021-05-23
  • 2012-02-13
相关资源
最近更新 更多