Divide large routes.rb to multiple files in Rails 5

本小妞迷上赌 提交于 2019-12-19 19:53:46

问题


I want to upgrade my rails 4 app to 5.0.0.beta2. Currently I divided the routes.rb file to multiple files by setting config.paths["config/routes.rb"] e.g.,

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

It seems rails 5.0.0.beta2 also exposes config.paths["config/routes.rb"] but the above code doesn't work. How can I divide routes.rb file in rails 5?


回答1:


you can write some codes in config/application.rb

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



回答2:


Here's a nice article, simple, concise, straight to the point - not mine.

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



回答3:


I like the method demonstrated in 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


来源:https://stackoverflow.com/questions/35609059/divide-large-routes-rb-to-multiple-files-in-rails-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!