Ruby Tip: Invoking a Class From its Name 1
Posted Monday, February 19, 2007 20:40
I wanted to pass the name of a class to a web page, and then on that page I wanted to create an instance of that class. I can’t pass the class itself, since URL parameters are simply strings. So there must be a way to create the class given its name as a string, right?
I didn’t finding it browsing my books or using Google (because I couldn’t find quite the right thing to search for), but of course Dave Thomas knew the answer immediately.
Like most things in programming, and in Ruby in particular, it’s simple once you know how to do it:
Module.const_get('classname')
delivers the class object, so
Module.const_get('classname').new
creates a new instance of the class.
const_get produces the value of a constant, and because classes in Ruby are constants, the value of the name of a class is the class itself. (But you all knew this, right?)
Comments
-
This has some limitations with regard to namespaces. This is explained, and a solution presented, in this article: http://redcorundum.blogspot.com/2006/05/kernelqualifiedconstget.html
