Ruby 访问Struct.new块中的类变量

Ruby 访问Struct.new块中的类变量,ruby,class-variables,Ruby,Class Variables,我正在使用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 = $

我正在使用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':未初始化的类变量@@base in Test::C(NameError)
来自test2.rb:24:in
new' 来自test2.rb:24:in`'

根据我对Struct.new的理解,块是在创建类的上下文中执行的,因此@base应该是可解析的

谢谢你的时间

编辑:
谢谢-我在self.init上创建了init_,并使用了class_variable_set而不是instance_variable_set。它现在起作用了

为什么不尝试使用类似于
self.instance\u variable\u set(:@@base,$base\u module)
。我认为这可能行得通,因为您只是在设置类对象的实例变量。

为什么不尝试使用类似于
self.instance\u variable\u set(:@@base,$base\u module)
。我认为这可能行得通,因为您只是在设置类对象的实例变量。

这不可能行得通,原因很简单,
@@base
显然不是实例变量。这不可能行得通,原因很简单,
@@base
显然不是实例变量。