There is a significant difference between instance variables and class instance variables.
class Test
@magic = "spell" # class instance var, since the scope is class
def initialize
@magic = 42 # instance var, scope is instance
end
end
Those two live together, since they are defined on different objects:
Test.instance_variable_get(:@magic) #⇒ "spell"
Test.new.instance_variable_get(:@magic) #⇒ 42
That said, attr_accessor reads the variable from the scope, it was defined for. Yours was defined in class scope, therefore it reads the instance scoped variable.
To read the class instance variable, define attr_accessor on class’ singleton class level:
class Test
singleton_class.send :attr_accessor, :magic # reads class instance var ⇓
@magic = "spell" # class instance var, since the scope is class
attr_accessor :magic # reads instance var ⇓
def initialize
@magic = 42 # instance var, scope is instance
end
end
Test.magic
#⇒ "spell"
Test.new.magic
#⇒ 42