accessing model class variables in a controller.

Hello,

Hello.

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 end

That's not how class variables work. I haven't read it, but word on the street is `Ruby for Rails' by David A. Black is a good resource for learning Ruby with Rails. The Pickaxe is fantastic also (google: Ruby Pickaxe).

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?

Yes. What you want is cattr_accessor. It works just like attr_accessor, but for class variables.

Class variables can be tricky. Check out this nutty blog post to understand their nuances: Sessions N Such — err.the_blog

Hi --

Hello,

Hello.

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 end

That's not how class variables work. I haven't read it, but word on the street is `Ruby for Rails' by David A. Black is a good resource for learning Ruby with Rails. The Pickaxe is fantastic also (google: Ruby Pickaxe).

I've responded in detail to Sam's question because my book, though I'm happy to see it recommended, says very little about class variables. I like to think it's not just because I dislike them, but also because I really haven't seen very many reasons to use them. People learning Rails will definitely want to know them when they see them, but beyond that I didn't have much to say about them.

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?

Yes. What you want is cattr_accessor. It works just like attr_accessor, but for class variables.

It's misnamed, though, because it implies that class variables can store object "attribute" values. Since they cut across many objects, they're not really representing any object's attributes.

Class variables can be tricky. Check out this nutty blog post to understand their nuances: Sessions N Such — err.the_blog

I've just added a response to that post, which will save some space here :slight_smile:

David

Great points and great comment. Thanks for the insight!

All of this makes this clear. I did want to mention that my use case for these class variables was not to actually write to them, but to just use them to define a set of possible values for a particular attribute in an object. In other words, they are sort of used as a constant, but within the scope of that class. I didn’t want to declare these outside of my model class as constants b/c there’s no reason why they should be available elsewhere.

If this design decision does not sound good, I’d like to know why.

Thanks.