ruby 将字符串中的类名转换为实际类 [英] ruby convert class name in string to actual class
本文介绍了ruby 将字符串中的类名转换为实际类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从包含类名的字符串中调用类?(我想我可以做 case/when 但这看起来很难看.)
How do I call a class from a string containing that class name inside of it? (I guess I could do case/when but that seems ugly.)
我问的原因是因为我正在使用 acts_as_commentable
插件等,这些插件将 commentable_type 存储为一列.我希望能够调用任何特定的可评论类来对其进行 find(commentable_id)
.
The reason I ask is because I'm using the acts_as_commentable
plugin, among others, and these store the commentable_type as a column. I want to be able to call whatever particular commentable class to do a find(commentable_id)
on it.
谢谢.
推荐答案
我想你想要的是 常量化
I think what you want is constantize
这是一个 RoR 结构.不知道有没有ruby core的
That's an RoR construct. I don't know if there's one for ruby core
这篇关于ruby 将字符串中的类名转换为实际类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文