gpt4 book ai didi

ruby-on-rails - 带有嵌套模块的 Object.const_set 中的常量名称错误

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

我有一堆模块想在命名空间中定义,我将它们放在初始化程序中,但我得到了“错误的常量名称”异常:

# this is a self-contained example
require 'active_support/all'
# ==> true

[:baz, :qux].each do |name|
Object.const_set("FooBar::#{name.to_s.camelize}", Module.new {
define_singleton_method :my_awesome_static_method do |amount|
DoSomething.calculate(amount)
end
})
end
# =NameError: wrong constant name FooBar::Baz
# = from (irb):4:in `const_set'
# = from (irb):4:in `block in irb_binding'
# = from (irb):3:in `each'
# = from (irb):3
# = from /usr/local/var/rbenv/versions/2.0.0-p353/bin/irb:12:in `<main>'

我认为我得到这个是因为初始化器在定义 FooBar 之前运行,但问题是如果我在这个初始化器中定义它,FooBar.constants 是空的,我不确定出了什么问题。

最佳答案

将您的代码包装在 Foobar 类或模块中:

module Foobar
%w[Baz Qux].each do |name|
const_set(name, Module.new {
define_singleton_method :my_awesome_static_method do |amount|
DoSomething.calculate(amount)
end
})
end
end

如果是类,则使用 class Foobar

这不会重新定义它或任何东西,只是打开它以在其命名空间中添加新类。请注意我是如何从 const_set 中删除 Object 和 Foobar 并使用 Ruby 的 %w[] 符号来定义字符串数组的,无需 to_s现在 Camel 化他们。

此外,它对您不起作用的原因既是在常量名称中使用了冒号,也是您通过 Object.const_set 而不是在 Object 上定义常量这一事实在 Foobar 上定义它们。这也将起作用:

%w[Baz Qux].each do |name|
Foobar.const_set(name, Module.new {
define_singleton_method :my_awesome_static_method do |amount|
DoSomething.calculate(amount)
end
})
end

假设 Foobar 已经被定义,即使 Foobar 还没有被加载,前面的例子也会工作。

关于ruby-on-rails - 带有嵌套模块的 Object.const_set 中的常量名称错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21895527/

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