accessing model class variables in a controller.

Hi --


In my model Example, I've defined three types as such:

class Example < ActiveRecord::Base
@@TYPE_A = 'A'
@@TYPE_B = 'B'
@@TYPE_C = 'C'


How can I access these types in my controller. I'm trying the following
with my controller named Read:

def exm
a = Example.TYPE_A

It won't allow me to declare the types and gives me a syntax error. Any
help would be appreciated. Aren't these just class variable
declarations and should be available through the class?

You're confusing class variables with constants, and constants with
methods :slight_smile:

Class variables (@@var) are variables with a scope that includes

   1. the class in whose scope they were created
   2. all descendants of that class
   3. all instances of any of those classes

What class variables *don't* have is any implication for methods; that
is, when you assign to a class variable, you're just assigning to a
variable, not creating any methods that either get or set the value of
that variable.

If you want such methods, you have to write them:

   class C
     def self.cvar_x # access the cvar from the class

     def cvar_x # access it from instances of the class

or create/use a facility for doing so, like the "cattr_*" methods that
are used internally in Rails.

By the way, the somewhat strange behavior of "class variables" -- in
particular, that they're not actually class-specific, but are more
class-hierarchy-specific -- is due to change in future versions of
Ruby. Then there are people like me, who think class variables cause
(and will continue to cause, even with that change) much more trouble
than they're worth, and wish they would go away entirely. But I don't
think Matz is in that camp :slight_smile: