gpt4 book ai didi

ruby-on-rails - Object.const_get 和 Rails - 切断父模块名称

转载 作者:太空宇宙 更新时间:2023-11-03 17:48:27 25 4
gpt4 key购买 nike

我有以下代码来提取和实例化 Rails Controller :

def get_controller(route)
name = route.requirements[:controller]
return if name.nil?


if name.match(/\//)
controller_name = name.split('/').map(&:camelize).join('::')
else
controller_name = name.camelize
end

p controller_name: controller_name

controller = Object.const_get("#{controller_name}Controller")

p controller: controller
controller.new
end

一些路由是单一名称——“用户”、“ friend ”、“邻居”、“政客”等...

其他路由是嵌套的,如“admin/pets”、“admin/shopping_lists”、“admin/users”等...

上面的代码在提到的大多数情况下都有效(因为它正确地构建和实例化了 Controller ),除了一个 - 在这个例子中,“admin/users”

puts 语句中,我得到以下信息:

{:controller_name=>"Admin::Users"}
{:controller => UsersController}

您会注意到命名空间 Admin 被切断了。我的猜测是,因为这只是在多个 namespace (usersadmin/users)中共享名称的 Controller 的情况,所以它与 Rails 自动加载有关( ?)。知道是什么原因造成的吗?

根据 lx00st 的评论,我还应该指出,我已经尝试了多种获取这些常量的形式,另一种尝试如下:

sections = name.split('/')
sections.map(&:camelize).inject(Object) do |obj, const|
const += "Controller" if const == sections.last
obj.const_get(const)
end

这种方法遇到了同样的问题。

最佳答案

这已通过用户 apneadiving 的答案解决,可以找到 here

Be aware that there are vicious cases in Rails development mode. In order to gain speed, the strict minimum is loaded. Then Rails looks for classes definitions when needed.

But this sometimes fails big time example, when you have say ::User already loaded, and then look for ::Admin::User. Rails would not look for it, it will think ::User does the trick.

This can be solved using require_dependency statements in your code.

我个人认为这是一个错误,而不是一个功能,但是......事实就是如此。它解决了这个问题。

关于ruby-on-rails - Object.const_get 和 Rails - 切断父模块名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29849501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com