动态创建转义常量(Ruby on Rails)

Dynamically create an escaped constant (Ruby on Rails)

我需要动态创建一个从当前命名空间转义出来的常量,所以我需要在我的常量前面加上'::'。但是,当我尝试以下操作时,出现以下错误...

def make_constant(type)     
  "::"+"#{type}".singularize.camelize.constantize
end

当我尝试像

这样的事情时

make_constant("MyModel") 结果应该是一个常数:

::MyModel

但是,我收到错误:

TypeError (no implicit conversion of Class into String)

In Ruby + 的优先级低于方法调用 .,因此您首先使用 "#{type}".singularize.camelize.constantize 创建一个 class 然后尝试添加这个 class 到失败的字符串 '::'

要修复它,您可以:

("::"+"#{type}".singularize.camelize).constantize # ugly, but proves the point
"::#{type.singularize.camelize}".constantize #elegant and working :)

您应该不需要在方法链上连接或使用括号

def make_constant type
  "::#{type}".singularize.camelize.constantize
end