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
:
class Rating
RATINGSCODES = %w{ G A AB TR P }
RATINGSCODES.each do |code|
const_set code, code
end
end
#=> ["G", "A", "AB", "TR", "P"]
p Rating::G
#=> "G"
If Rating::G
works for you, Raiting.const_get('G')
also will.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With