Can getter/setter be auto-generated/enabled for class variables like that are being generated for instance variables using attr_accessor
:
class School
@@syllabus = :cbse
def self.syllabus
@@syllabus
end
def self.syllabus=(_)
@@syllabus = _
end
end
School.syllabus = :icse
School.syllabus # => :icse
All you need to do is to declare the attr_accessor
in the scope of the class:
class School
class << self
attr_accessor :syllabus
end
end
School.syllabus = :icse
School.syllabus # => :icse
Be aware though that the underlying member will not be @@syllabus
(there is no built in solution for these kind of variables) but @syllabus
in the class scope, which is the recommended way to do it anyway, see this blog post on the difference between the two:
The issue with class variables is inheritance. Let’s say I want to subclass Polygon with Triangle like so:
class Triangle < Polygon @@sides = 3 end puts Triangle.sides # => 3 puts Polygon.sides # => 3
Wha? But Polygon’s sides was set to 10? When you set a class variable, you set it for the superclass and all of the subclasses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With