tags:

views:

431

answers:

1

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?

+1  A: 

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
Ian Terrell
Thanks for your reply. Actually I know how to make this in Ruby only-the problem is to supply setter/getter and store the stuff in a C variable per class instance. I need the value in C and don't want to copy it between Ruby and C over and over again.
unexist