【问题标题】:Dynamically create an escaped constant (Ruby on Rails)动态创建转义常量(Ruby on Rails)
【发布时间】:2019-09-04 21:54:07
【问题描述】:

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

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

当我尝试类似的事情时

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

::MyModel

但是,我得到了错误:

TypeError(没有将 Class 隐式转换为 String)

【问题讨论】:

  • 我认为它们不应该是“元编程”标签。

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


【解决方案1】:

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

要修复它,您可以:

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

【讨论】:

  • 优雅选项不起作用,因为camelize的操作方式与顶级版本不同。
  • 感谢 @user2012677 通过在插值内移动它来修复它
【解决方案2】:

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

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

【讨论】:

  • "::word".camelize = "::word",其中 "::"+'word'.camelize = ::Word
猜你喜欢
  • 2013-12-21
  • 1970-01-01
  • 1970-01-01
  • 2015-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-03
  • 2011-08-01
相关资源
最近更新 更多