ruby-on-rails - 动态创建转义常量(Ruby on Rails)
问题描述
我需要动态创建一个从当前命名空间中转义的常量,所以我需要在常量前面加上'::'。但是,当我尝试以下操作时,出现以下错误...
def make_constant(type)
"::"+"#{type}".singularize.camelize.constantize
end
当我尝试类似的事情时
make_constant("MyModel")
结果应该是一个常数:
::MyModel
但是,我得到了错误:
TypeError(没有将类隐式转换为字符串)
解决方案
在 Ruby+
中,优先级低于方法调用.
,因此您首先创建一个类,"#{type}".singularize.camelize.constantize
然后尝试将该类添加到'::'
失败的字符串中。
要修复它,您可以:
("::"+"#{type}".singularize.camelize).constantize # ugly, but proves the point
"::#{type.singularize.camelize}".constantize #elegant and working :)
推荐阅读
- javascript - 动态 HTML 复选框上的“全选”复选框
- robotics - 在 Pepper 中,如何备份并擦除现有包?
- python - 从特殊字符列表中提取整数
- sql - 在 Oracle SQL 中搜索多个字符串
- vba - 如何在vba中定义公式?
- netsuite - 无法在套件脚本 2.0 中从客户端向套件发布数据
- vba - 将变量从 vba 传递到 .bat 文件
- python - Python。Tor 浏览器。虚拟专用网。代理人
- python - 如何在 celery worker 中一次只执行一项任务,而不会丢失它并保持队列中任务的顺序
- sql - SQL 字符串转 int(日期)