However, I’d like to be able to create a class variable that is easily
accessible (read/write) by outside users without having to write class
accessor methods. How can I do this?
A really ugly way to set the variable without an accessor would be
this:
class Foo; @@class_constant = “newvalue” end
but that is write only.
The syntax:
Foo.class_constant = “newvalue”
would be preferable, but how to do this without writing accessor
methods?
accessible (read/write) by outside users without having to write class
methods?
One way or another, if you want a class variable set when you call the
method class_constant=, then that method has to set the variable.
See Ara’s answer; you’re almost certainly better off using a real
attr_accessor operation on the class object. (Yes, as I pointed out,
it doesn’t match the question exactly, but it’s an improvement
class C
class << self
attr_accessor ‘class_constant’
end
end
For an intermediate ruby user, could you explain what is happening in
the line: ‘class << self’
search the archives - this comes up about once per week. for now,
suffice it
do say that
class C
class << self
# everthing here is at class scope
@a_class_instance_variable = 42
def a_class_method() @a_class_instance_variable end
alias_method 'one_class_method', 'to_another'
extend ABunchOfClassMethods
end
end
accessible (read/write) by outside users without having to write class
methods?
Thanks
Here’s the Rails implementation if you just want to see one working
implementation. Note that it allows you to access the class attribute
from the class and from instances (which is similiar to static members
in Java, actually).
class C
class << self
attr_accessor ‘class_constant’
end
end
For an intermediate ruby user, could you explain what is happening in
the line: ‘class << self’
The expression:
class << obj
puts you in a class definition block for the singleton class of obj.
The singleton class of obj is where obj’s singleton methods live –
that is, the methods that only obj can call.
obj = Object.new
def obj.x
“Singleton method on obj”
end
class << obj
puts instance_methods(false) # methods defined in this class only
end
Output: x
You can also define methods inside the class definition block, of
course:
class << obj
def y
“Another singleton method on obj”
end
end
class C
class << self
attr_accessor ‘class_constant’
end
end
require ‘facet/functor’
module Kernel
# Provides access to an object's metaclass (ie. singleton)
# by-passsing access provisions. So for example:
#
# class X
# meta.attr_accesser :a
# end
#
# X.a = 1
# X.a #=> 1
def meta
@_meta_functor ||= Functor.new do |op,*args|
(class << self; self; end).send(op,*args)
end
end
end
T.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.