Question

I need to create an object from its name from as a string (ie. a value in some JSON). I know I can use:

classname = 'MyClass' 
eval classname

and the much better:

classname = 'MyClass'
obj = Kernel.const_get(classname)

but since this is Ruby I was wondering if there were other alternatives (and perhaps more subjectively elegant ways) to achieving this goal.

Était-ce utile?

La solution

So I've scoured the net, and the short answer is "no".

There is however a Kernel#qualified_const_get written by a "Gregory" which is kinda neat since it can get nested classes, but this obviously isn't native Ruby.

I found that little snippet from an awesome blog "Electric Sheep" by Sidu Ponnappa - who has done a magnificent writeup on using all three methods "Loading classes from strings in Ruby" - the conclusion being:

Here are three choices when trying to convert a string to the corresponding class: Kernel#const_get, eval and Kernel#qualified_const_get

  1. Kernel#const_get is the fastest, doesn't handle nested classes and works for all but the weirdest of scenarios (the class you're trying to get hold of isn't a named constant)

  2. eval is significantly slower, but it works in any situation

  3. Kernel#qualified_const_get is abysmally slow, but handles nested classes. However, until there is a native implementation, it loses to eval on every front

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top