ruby-on-rails - 多条路线文件 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
解决方案
在 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 中所做的一样
推荐阅读
- c# - 执行不等待条件
- node.js - 使用节点js将react-native应用程序中的图像上传到s3
- windows - 在 docker 中挂载本地文件夹会导致目录为空
- python-3.x - 在这种情况下如何使用 args 来防止函数的多次调用?
- amp-html - 删除 WordPress 插件后 Google AMP 网站仍然显示
- cvs - Retrieve the author of the last-committed revision of a file in CVS
- excel - How do I vertically stack tables in SAS using ODS Excel?
- r - 阅读 bibliometrix 的多个围兜
- bash - Bash 参数扩展无法匹配 $* 和 $@ 等变量中的空格
- python - pytype 为(显然)有效的类方法返回 bad-concrete-type