2
我正在使用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:在initialize': uninitialized class variable @@base in Test::C (NameError) from test2.rb:24:in
新的」 從test2.rb:24: '
根據我對Struct.new的理解,該塊是在正在創建的類的上下文中執行的,所以@@ base應該是可解析的。
謝謝你的時間!
編輯: 謝謝 - 我做了init_on self.init_on並使用了class_variable_set而不是instance_variable_set。它現在工作!
這不可能是因爲`@@ base`明顯不是一個實例變量。 – 2011-02-04 20:34:57