Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can Ruby's attr_accessor produce class variables or class instance variables instead of instance variables?

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?

like image 316
pez_dispenser Avatar asked May 21 '09 23:05

pez_dispenser


People also ask

What is the difference between class variable and instance variable in Ruby?

What is the difference between class variables and class instance variables? The main difference is the behavior concerning inheritance: class variables are shared between a class and all its subclasses, while class instance variables only belong to one specific class.

Can a Ruby module have instance variables?

Explanation: Yes, Module instance variables are present in the class when you would include them inside the class.

How do instance variables work in Ruby?

In the Ruby programming language, an instance variable is a type of variable which starts with an @ symbol. An instance variable is used as part of Object-Oriented Programming (OOP) to give objects their own private space to store data. We say that objects can: Do things.

How does Attr_accessor work in Ruby?

In Ruby, object methods are public by default, while data is private. To access and modify data, we use the attr_reader and attr_writer . attr_accessor is a shortcut method when you need both attr_reader and attr_writer .


1 Answers

Like this:

class TYourClass   class << self     attr_accessor :class_instance_variable   end end 

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 class Class, it adds two methods to the class, one which reads the instance variable, and other that sets it. Here's a possible implementation:

class Class   def my_attr_accessor(name)     define_method name do       instance_variable_get "@#{name}"     end      define_method "#{name}=" do |new_val|       instance_variable_set "@#{name}", new_val     end   end end 

Completely untested class attribute accessor:

class Class   def class_attr_accessor(name)     define_method name do       class_variable_get "@@#{name}"     end      define_method "#{name}=" do |new_val|       class_variable_set "@@#{name}", new_val     end   end end 
like image 156
krusty.ar Avatar answered Oct 01 '22 13:10

krusty.ar