开发者

In Ruby, is there a better way of selecting a constant (or avoiding the constant altogether) based on an incoming string of the same name?

Not sure the title fully describes the problem/quest开发者_如何学Goion I'm trying to ask, sorry.

One of my fellow developers has created classes as such:

class Widget
  attr_accessor :model_type
  ...
end

and:

class ModelType
  MODEL1 = "model1"
  MODEL2 = "model2"
  MODEL3 = "model3"
end

Now he wants me to convert a retrieved string "MODEL1" to the constant. So that when he is referencing that model elsewhere he can use ModelType::MODEL1 (EDIT: The incoming string will be the name of the constant exactly). Obviously I've got to convert from the string I'm being given with something like the following:

case model_type
  when 'MODEL1'
    @model_type = ModelType::MODEL1
  ...
end

I feel like this is clunky, so I'd like to know if there is a better DRYer way of providing this kind of functionality.


>> ModelType.const_get("MODEL1")

=> "model1"

Module const_get() rdoc

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜