Defining an accessor for the same class instance variable for a set of subclasses in Ruby

StackOverflow https://stackoverflow.com/questions/11603508

  •  22-06-2021
  •  | 
  •  

Question

I have a superclass and a set of subclasses. In each subclass, I am defining a class instance variable that has the same name x. To create an accessor for one of these classes, I would just use in the subclass definition:

class << self
  attr_accessor :x
end

I would like to avoid using these same lines of code in all of my subclass definitions. But if I put this in the superclass definition, then won't it define an accessor for the instance variable of the superclass? That's not what I want. Is there a way to define an accessor for class instance variables of all subclasses in one place?

Était-ce utile?

La solution

Remember, that attr_accessor directive actually defines two methods: x() and x=(). Now, if you declare two public methods in your superclass, will they be available in subclasses? The answer is yes, unless you redefine them.

So putting this directive in superclass is just fine and will work a charm.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top