Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getter/Setter for class variables in Ruby

Tags:

ruby

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
like image 796
Jikku Jose Avatar asked Feb 12 '23 06:02

Jikku Jose


1 Answers

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.

like image 65
Uri Agassi Avatar answered Feb 13 '23 18:02

Uri Agassi