Is there a way to have class variables with setter/getter like virtual variables?
Question
I am embedding Ruby into my C project and want to load several files that define a class inherited from my own parent class. Each inherited class needs to set some variables on initialization and I don't want to have two different variables for Ruby and C.
Is there a way to define a class variable that has an own custom setter/getter or is this a stupid way to handle it? Maybe it would be better with a custom datatype?
Solution
I'm not sure exactly what you're asking. Of course class variables can have getters and setters (and behind the scenes you can store the value any way you like). Does this snippet help illuminate anything?
>> class TestClass
>> def self.var
>> @@var ||= nil
>> end
>> def self.var=(value)
>> @@var = value
>> end
>> end
=> nil
>>
?> TestClass::var
=> nil
>> TestClass::var = 5
=> 5
>> TestClass::var
=> 5
If you're into the whole metaprogramming thing, you can implement a class_attr_accessor method similar to the attr_accessor method. The following is equivalent to the above code.
class Module
def class_attr_accessor(attribute_name)
class_eval <<-CODE
def self.#{attribute_name}
@@#{attribute_name} ||= nil
end
def self.#{attribute_name}=(value)
@@#{attribute_name} = value
end
CODE
end
end
class TestClass
class_attr_accessor :var
end