I need to get a reference to a class object from a string with the name of
the class. I want to do this in a secure way because the string comes from
an external source. I could not find any easy way to convert a string or
symbol to a class reference. I found two approaches though:

1. Using eval

class NoSuchClassError < Exception; end
class NotClassError < Exception; end

def findClass(classname)
  raise NotClassError unless classname =~ /^[A-Z]\w*$/
  begin
    eval(classname)
  rescue NameError
    raise NoSuchClassError
  end
end

2. Using ObjectSpace::each_object(Class)

class NoSuchClassError < Exception; end

def findClass(classname)
  each_object(Class) { |obj|
    return obj if obj.name == classname
  }
  raise NoSuchClassError
end

I dislike using eval() due to security concerns. Although I catch strings
such as 'system("rm *")' using the regular expression, what about
everything else that evaluates in the context, like constants?

Using each_object(class) is very inefficient, especially when there is
many classes.

Did I overlook some easy way to look up a symbol or string in the
namespace of Classes?

-- 
Lars Christensen, larsch / cs.auc.dk