首页 > 解决方案 > 多条路线文件 rails 5

问题描述

我有以下代码

应用程序.rb

config.autoload_paths += %W(#{config.root}/config/routes)

路线.rb

Rails.application.routes.draw do
  root to: 'summary#index'

  extend General
end

/config/routes/general.rb

module General
  def self.extended(router)
    router.instance_exec do

      # devise routes
      devise_for :users, controllers: { sessions: 'users/sessions' }
    end
  end
end

uninitialized constant General在加载应用程序时得到。

我正在使用 Ruby 2.2.6 和 Rails 5.0.2

标签: ruby-on-railsruby

解决方案


在 rails 6 中,您可以使用draw(:general),它将在 config/routes/general.rb 中查找路由定义

您可以使用初始化程序来模拟它:

module RoutesSubfolder
  # Extension to Rails routes mapper to provide the ability to draw routes
  # present in a subfolder
  #
  # Another solution would be to add the files to `config.paths['config/routes']`
  # but this solution guarantees the routes order
  #
  # Example: <config/routes.rb>
  #
  #   Rails.application.routes.draw do
  #     # this will eval the file config/routes/api.rb
  #     draw :api
  #
  # Example:
  #   draw :'api/whatever' # loads config/routes/api/whatever.rb
  #
  def draw(name)
    path = Rails.root.join('config', 'routes', "#{name}.rb")

    unless File.exist?(path)
      raise StandardError, "Unable to draw routes from non-existing file #{path}"
    end

    instance_eval(File.read(path), path.to_s, 1)
  end
end

ActionDispatch::Routing::Mapper.prepend(RoutesSubfolder)

与您提出的唯一区别是:

  • 你不需要改变 autoload_path
  • 在 general.rb 中,您直接声明您的路由,就像您在Rails.application.routes.draw do块内的 config/routes.rb 中所做的一样

推荐阅读