Posted by Matt Williams
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:
1
2
3
4
5
6
7
8
9
10
11
12
|
class Module
def class_attr_lookup
self.find(:all).each do |rec|
r = rec.name.downcase.underscore
self.class.send(:define_method, r) do
self.class_eval "@@#{r}"
end
self.class_eval "@@#{r} = rec"
end
end
end
|
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:
1
2
3
4
5
|
class State < ActiveRecord::Base
class_attr_lookup
validates_presence_of :name
end
|
Then to access the
RUNNING record, you'd use
State.running.
Enjoy!