Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a constant value from a string

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
like image 267
Mutuelinvestor Avatar asked Feb 20 '23 18:02

Mutuelinvestor


2 Answers

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" 
like image 125
jaredonline Avatar answered Mar 07 '23 22:03

jaredonline


If Rating::G works for you, Raiting.const_get('G') also will.

like image 26
J-_-L Avatar answered Mar 07 '23 23:03

J-_-L