I want do do something like this
class MyClass
def default
self.default
end
def self.default
return @@default if @@default
self.default = ‘this’
end
def self.default=(value)
@@default = value
end
end
a = MyClass.new
=> nil
a.default
=> “this”
But, this does not work. What is the idiom to get this to happen?
On Jun 2, 9:31 pm, James B. [email protected]
wrote:
I want do do something like this
class MyClass
def default
self.default
end
this creates an infinite recursion - self.default doesn’t call the
class method, it’s equivalent to writing
def default
default
end
which obviously doesn’t work.
You could write
def default
MyClass.default
end
or, equivalently
def default
self.class.default
end
the code as is won’t quite work, since ruby will complain if you try
to access an unset class variable, so you need some thing like
class MyClass
@@default = 'this
…
end
@@ variables are visible by instances as well as classes though, so
you could also do
def default
@@default
end
Lastly, active support already includes the cattr_accessor helper that
will create accessors for you
Fred
I found this subject well explained in this rather enlightening post
attributed to DHH:
http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/51023b181ab950dc
Frederick C. wrote:
Lastly, active support already includes the cattr_accessor helper that
will create accessors for you
Ahh, I had run across this before but I could not remember what it was
called or where it was found. Thanks for the lucid explanation about
the rest of it as well.
Regards,