If I have a class with an attr_accessor
, it defaults to creating an instance variable along with the corresponding getters and setters. But instead of creating an instance variable, is there a way to get it to create a class variable or a class instance variable instead?
Ruby – How to Ruby’s attr_accessor produce class variables or class instance variables instead of instance variables
class-instance-variablesclass-variablesinstance-variablesruby
Related Question
- Ruby-on-rails – How to get the name of a Ruby class
- Ruby: Calling class method from instance
- Java – How do servlets work? Instantiation, sessions, shared variables and multithreading
- Ruby – Difference between class variables and class instance variables
- Ruby – Why use Ruby’s attr_accessor, attr_reader and attr_writer
- Ruby class instance variable vs. class variable
Best Solution
Like this:
You can look at this as opening the metaclass of the class (of which the class itself is an instance) and adding an attribute to it.
attr_accessor
is a method of classClass
, it adds two methods to the class, one which reads the instance variable, and other that sets it. Here's a possible implementation:Completely untested class attribute accessor: