在字符串和类名之间转换 [英] Cast between String and Classname
本文介绍了在字符串和类名之间转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串,其中包含一个类名.例如,它是一个包含Article"的字符串.该字符串来自 params[].我应该如何处理这个字符串,就好像它是一个类名一样?例如,我想做:
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
等等.
有什么想法吗?
推荐答案
此解决方案优于 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.
# Monkey patch for String class
class String
def to_class
klass = Kernel.const_get(self)
klass.is_a?(Class) ? klass : nil
rescue NameError
nil
end
end
# Examples
"Fixnum".to_class #=> Fixnum
"Something".to_class #=> nil
更新 - 与命名空间一起使用的更好版本:
# Monkey patch for String class
class String
def to_class
chain = self.split "::"
klass = Kernel
chain.each do |klass_string|
klass = klass.const_get klass_string
end
klass.is_a?(Class) ? klass : nil
rescue NameError
nil
end
end
这篇关于在字符串和类名之间转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文