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

偶尔善良 提交于 2019-11-28 04:09:08

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
Charles Dale

In Rails, (or anywhere you do require 'active_support') you can use cattr_accessor :name to get the true class variable accessors.

The class instance variables that others have pointed out are usually more useful. The APIdock cattr_accessor page has some helpful discussion clarifying when you would want one not the other, plus the source to the cattr_accessor, cattr_reader and cattr_writer functions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!