I'm writing a piece of software where I receive the name of an active
record class from the outside (in the request_uri) and want to make a
lookup on whether this active record class exists. Then, I need to do a
.find(...) and whatever on that class.
The following lines do exactly what I want, however, they are
completely *NOT* secure
activerecord = eval(name)
if activerecord.superclass == ActiveRecord::Base
Anyone has a better idea?
A switch/case is not an option as I don't know the names of all
existing active record classes at design time. However, could one find
out the names of all available active record classes at run time?
ActiveRecord::Base only finds out about its subclasses when they are loaded. I think it's easier to follow your approach, finding the named class (if there is one), and then finding out if its superclass is ActiveRecord::Base. (Note that if you start introducing inheritance among your model classes you will need to extend this to look beyond the direct superclass.)
c = name.constantize rescue nil
if c.class == Class && c.superclass == ActiveRecord::Base
Rails adds the constantize method to String, to return the value of the constant named by the String. If there isn't one, it raises a NameError exception - the "rescue nil" clause catches this.
In the if statement, c could be nil, or some non-class constant value, or a class - so a check that it's a class is needed before trying to invoke its superclass method.