Search code examples
rubyclass-variables

Accessing a class variable in Struct.new block


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) from test2.rb:24:innew' 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!


Solution

  • 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.