如何将符号或字符串转换为正确的类名

时间:2015-01-12 06:58:15

标签: ruby ruby-on-rails-4

我有一个带有命名空间的类,我希望通过转换给定的字符串来获取该类的名称,这是最好的方法。下面是我的班级和相应的字符串

module Test
 class Myclass
 end 
end

我想从字符串中获取上面的类名,如下所示

string = "test_myclass", I want to convert this in to Test::Myclass

此外,字符串不是固定的,其动态例如它需要转换下面的字符串 作为TestMyclass,如果类" TestMyclass"存在于rails app

 class TestMyclass
 end 

string = "test_myclass", convert this in to TestMyclass

1 个答案:

答案 0 :(得分:1)

您可以使用#camelize方法将类名称作为字符串:

string = "test_myclass"
string.gsub('_', '/').camelize
# => "Test::Myclass"

然后,#constantize它:

string = "test_myclass"
string.gsub('_', '/').camelize.constantize
# => Test::Myclass

对于您的更新问题,您可以使用

检查TestMyclass是否存在
string = "test_myclass"
klass = begin
  # trying TestMyclass, if it doesn't exit
  # this will raise "NameError: uninitialized constant TestMyclass" 
  string.camelize.constantize
rescue NameError
  # if TestMyclass was not found, pick Test::Myclass
  string.gsub('_', '/').camelize.constantize
end