Set constant value from string

I have domain data in my rails application in which I am trying to create some constants. This is what I came across in Dan Chak Enterprise Rails Chapter 7. I did the following:

G = Rating.find_by_rating_code('G')

then when I use Rating :: G, the corresponding rating entry is returned. This works great. My problem arises from the fact that I have 150 rating codes. So instead of typing the above line of code for each of my rating codes, I was hoping to use a small meta program to avoid cluttering my model with a lot of redundant code. So 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

, , . . const_get, .

code.const_set = Rating.find_by_rating_code(code)

:

undefined method `const_set=' for "G":String
+3
2

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" 
+6

Rating::G , Raiting.const_get('G') .

+1

All Articles