Forum: Ruby on Rails Idiom for Class variables

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
James B. (Guest)
on 2009-06-03 00:31
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?
Frederick C. (Guest)
on 2009-06-03 01:14
(Received via mailing list)
On Jun 2, 9:31 pm, James B. <removed_email_address@domain.invalid>
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
James B. (Guest)
on 2009-06-03 18:03
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,
James B. (Guest)
on 2009-06-03 23:28
I found this subject well explained in this rather enlightening post
attributed to DHH:

http://groups.google.com/group/rubyonrails-talk/br...
This topic is locked and can not be replied to.