This post originated from an RSS feed registered with Ruby Buzz
by Matt Williams.
Original Post: class_attr_lookup
Feed Title: Subverting the Paradigm
Feed URL: http://subvertingtheparadigm.ottercat.net/feed/rss.xml
Feed Description: Which Paradigm? Pretty much all of them. It's about programming, exploring, management theory, development, and other radical notions. One day I'll talk about Ruby. The next day Rails. Javascript will be thrown in for good measure. Maybe even (gasp!) some Java. Thoughts about management style, too. A little bit of this, a little bit of that, all thrown together in a subversive attempt to change the world, but in a good way.
I had a situation where I had configuration and/or control values in a database and I didn’t want to have to read them over and over again, so I’ve created the following.
For example, if I had a states table with the following values:
RUNNING
STARTING
STARTED
STOPPED
UNKNOWN
STOPPING
These values are used througout the database and the code as lookup values and my development database is not the same type of database as what is used in production, so rather than having to look them up each time because I can’t count on the id being the same in all cases, I’m using State.running to represent the RUNNING record in the states table.
Here’s the code:
123456789101112
classModuledefclass_attr_lookupself.find(:all).each do |rec| r = rec.name.downcase.underscoreself.class.send(:define_method, r) doself.class_eval "@@#{r}"endself.class_eval "@@#{r} = rec"endendend
I know that I could have used class_variable_get and class_variable_set, but I’m using both JRuby and MRI and at the time this was written there was a bug in JRuby and class_variable_get wasn’t implemented.
To use it, add class_attr_lookup to the model, like this: