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

时间:2016-02-24 17:31:24

标签: ruby-on-rails-5

我想将我的rails 4 app升级到5.0.0.beta2。目前,我通过设置routes.rb例如

config.paths["config/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文件?

4 个答案:

答案 0 :(得分:6)

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

config.paths ['config / routes.rb']。concat Dir [Rails.root.join(“config / routes / * .rb”)]

答案 1 :(得分:6)

CONCAT_WS() - 不是我的。

  

配置/ application.rb中

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

配置/路由/ 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
     

配置/ routes.rb中

  Rails.application.routes.draw do
    extend AdminRoutes

    # A lot of routes
  end

答案 2 :(得分:3)

采用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

draw(:admin)块内部调用Rails.application.routes.draw会尝试加载与给定参数同名的路由文件(在这种情况下为admin.rb)。该文件必须位于config/routes目录或任何子目录(即config/routes/admin.rbconfig/routes/external/admin.rb)中。

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


Link to the corresponding PR

答案 3 :(得分:1)

我喜欢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