I have some domain data in my rails application that I’m trying to create some constants for. This is something I came across in Dan Chak’s Enterprise Rails Chapter 7. I have done the following:
G = Rating.find_by_rating_code('G')
then when I use Rating::G the appropriate Rating Record is returned. This works great. My problem arises due to the fact that I have 150 ratings codes. So instead of typing the above line of code for each of my ratings codes, I was hoping to use a little meta programing to avoid cluttering up my model with a lot of redundant code. Therefore I tried the following.
RATINGSCODES = %w(G A AB TR P ...)
class << self
RATINGSCODES.each do |code|
code.constantize = Rating.find_by_rating_code(code)
end
end
Unfortunately, I’m getting an uninitialized constant error and can’t figure out where I’m going wrong. Am I approaching this the right way. I also tried using const_get but that didn’t seem to work either.
At the suggestion below, I have also tried using
code.const_set = Rating.find_by_rating_code(code)
This yielded the following error:
undefined method `const_set=' for "G":String
Use
const_set: