This solution is better than eval because you are evaluating a params hash that can manipulate the user and may contain harmful actions. Generally: Never evaluate a userβs input directly, this is 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
Update is the best version that works with namespaces:
# 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
khelll Sep 19 '09 at 11:17 2009-09-19 11:17
source share