从字符串中设置常量值

Mut*_*tor 4 ruby ruby-on-rails-3

我在rails应用程序中有一些域数据,我正在尝试为其创建一些常量.这是我在Dan Chak的Enterprise Rails第7章中遇到的问题.我做了以下事情:

G = Rating.find_by_rating_code('G')
Run Code Online (Sandbox Code Playgroud)

然后当我使用Rating :: G时,返回适当的评级记录.这非常有效.我的问题出现是因为我有150个评级代码.因此,我没有为每个评级代码键入上面的代码行,而是希望使用一些元编程来避免使用大量冗余代码来混淆我的模型.因此,我尝试了以下内容.

RATINGSCODES = %w(G A AB TR P ...)

class << self
RATINGSCODES.each do |code|
code.constantize = Rating.find_by_rating_code(code)
end
end
Run Code Online (Sandbox Code Playgroud)

不幸的是,我得到了一个未初始化的常量错误,无法弄清楚我哪里出错了.我是否以正确的方式接近这一点.我也试过使用const_get,但似乎也没有用.

根据下面的建议,我也尝试过使用

code.const_set = Rating.find_by_rating_code(code)
Run Code Online (Sandbox Code Playgroud)

这产生了以下错误:

undefined method `const_set=' for "G":String
Run Code Online (Sandbox Code Playgroud)

jar*_*ine 7

用途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" 
Run Code Online (Sandbox Code Playgroud)