首页 > 解决方案 > 动态创建转义常量(Ruby on Rails)

问题描述

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

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

当我尝试类似的事情时

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

::MyModel

但是,我得到了错误:

TypeError(没有将类隐式转换为字符串)

标签: ruby-on-railsrubymetaprogrammingruby-on-rails-5.2

解决方案


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

要修复它,您可以:

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

推荐阅读