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 str
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
Update - a better 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