访问 Struct.new 块中的类变量
我正在使用 Struct.new 动态创建新类(我们正在使用一些实体建模中间件,我想动态生成具体类型以进行序列化)。
本质上我有这段代码:
module A
def self.init_on(target)
target.foo = 123
end
end
$base_module = A
module Test
C = Struct.new(:id) do
include $base_module
@@base = $base_module
def initialize
@@base.init_on(self)
end
attr_accessor :foo
end
end
c = Test::C.new
puts c.foo
当我运行测试时出现此错误:
test2.rb:17:in initialize': uninitialized class variable @@base in Test::C (NameError) 来自 test2.rb:24:in
new' from test2.rb:24:in `'
根据我对 Struct.new 的理解,该块是在正在创建的类的上下文中执行的,因此 @@base 应该是可解析的。
感谢您抽出时间!
编辑: 谢谢 - 我做了 init_on self.init_on 并使用了 class_variable_set 而不是 instance_variable_set。现在可以了!
I'm using Struct.new to create new classes on the fly (we're using some entity modelling middleware, and I want to generate concrete types on the fly for serialization).
In essence I have this code:
module A
def self.init_on(target)
target.foo = 123
end
end
$base_module = A
module Test
C = Struct.new(:id) do
include $base_module
@@base = $base_module
def initialize
@@base.init_on(self)
end
attr_accessor :foo
end
end
c = Test::C.new
puts c.foo
I get this error when I run my test:
test2.rb:17:in initialize': uninitialized class variable @@base in Test::C (NameError)
new'
from test2.rb:24:in
from test2.rb:24:in `'
From my understanding of Struct.new, the block is executed with the context of the class being created, so @@base should be resolvable.
Thanks for your time!
Edit:
Thanks - I made init_on self.init_on and used class_variable_set rather than instance_variable_set. It now works!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么不尝试使用类似
self.instance_variable_set(:@@base, $base_module)
的东西。我认为这可能有效,因为您只是设置类对象的实例变量。Why not try to use something like
self.instance_variable_set(:@@base, $base_module)
. I think that may work, since you are just setting an instance variable of the class object.