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?
相关问题
- How to specify memcache server to Rack::Session::M
- Why am I getting a “C compiler cannot create execu
- reference to a method?
- ruby 1.9 wrong file encoding on windows
- gem cleanup shows error: Unable to uninstall bundl
相关文章
- Ruby using wrong version of openssl
- Difference between Thread#run and Thread#wakeup?
- how to call a active record named scope with a str
- “No explicit conversion of Symbol into String” for
- Segmentation fault with ruby 2.0.0p247 leading to
- How to detect if an element exists in Watir
- uninitialized constant Mysql2::Client::SECURE_CONN
- ruby - simplify string multiply concatenation
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:
In Rails, (or anywhere you do
require 'active_support'
) you can usecattr_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 thecattr_accessor
,cattr_reader
andcattr_writer
functions.