在字符串和类名之间进行转换
我有一个字符串,其中包含类名。例如,它是包含“Article”的字符串。该字符串来自 params[]。我应该怎么做才能像类名一样使用这个字符串?比如我想做:
Article.all
等等。
有什么想法吗?
I have a string, containing an Class name. It is, for example, a string containing "Article". That string came up from the params[]. What should I do to work with this string as if it was a class name? For instance, I want to do:
Article.all
and so on.
Any idea?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
此解决方案比 eval 更好,因为您正在评估可能被用户操纵并可能包含有害操作的 params 哈希值。作为一般规则:永远不要直接评估用户输入,这是一个很大的安全漏洞。
更新 - 与命名空间一起使用的更好版本:
This solution is better than eval as you are evaluating params hash that might be manipulated by the user and could contain harmful actions. As a general rule: Never evaluate user input directly, that's a big security hole.
Update - a better version that works with namespaces:
假设确实存在一个提供名称的类...
在 ActiveSupport 中,有 String#constantize,它做了同样的事情,但我相信它在 2.1 之后已被弃用。
编辑:这是 ActiveSupport 2.1.2 中的 Constantize 实现:
Assumes there really is a class with the name provided...
In ActiveSupport, there was String#constantize, which did the same thing, but I believe it's deprecated after 2.1.
EDIT: this is the implementation of constantize from ActiveSupport 2.1.2:
我不确定我是否正确理解了你的意图。这里我假设
all
是Article
的类方法,并且all
返回一个文章数组。I am not sure whether I understand your intention correctly. Here I assume
all
is an Class method ofArticle
andall
return an array of articles.