Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a class by name in Ruby?

Tags:

ruby

Having a string with the module and name of a class, like:

"Admin::MetaDatasController" 

how do I get the actual class?

The following code works if there's no module:

Kernel.const_get("MetaDatasController") 

but it breaks with the module:

ruby-1.8.7-p174 > Kernel.const_get("Admin::MetaDatasController") NameError: wrong constant name Admin::MetaDatasController         from (irb):34:in `const_get'         from (irb):34 ruby-1.8.7-p174 >  
like image 462
pupeno Avatar asked Jul 02 '10 06:07

pupeno


People also ask

How do I find the class of an object in Ruby?

Use #is_a? to Determine the Instance's Class Name in Ruby If the object given is an instance of a class , it returns true ; otherwise, it returns false . #is_a also returns true if the object is an instance of any subclasses.

What is the parent class Ruby?

But from Ruby 1.9 version, BasicObject class is the super class(Parent class) of all other classes in Ruby. Object class is a child class of BasicObject class.

What is IS_A in Ruby?

The is_a? method will return a true value if an object is a of the type given as a parameter OR if it inherits from the type given as a parameter. So in effect, you can use it to ask "is there going to be a method from a class which I can run on this object".

How do you check the type of a variable in ruby?

The proper way to determine the "type" of an object, which is a wobbly term in the Ruby world, is to call object. class . Since classes can inherit from other classes, if you want to determine if an object is "of a particular type" you might call object.


1 Answers

If you want something simple that handles just your special case you can write

Object.const_get("Admin").const_get("MetaDatasController") 

But if you want something more general, split the string on :: and resolve the names one after the other:

def class_from_string(str)   str.split('::').inject(Object) do |mod, class_name|     mod.const_get(class_name)   end end  the_class = class_from_string("Admin::MetaDatasController") 

On the first iteration Object is asked for the constant Admin and returns the Admin module or class, then on the second iteration that module or class is asked for the constant MetaDatasController, and returns that class. Since there are no more components that class is returned from the method (if there had been more components it would have iterated until it found the last).

like image 51
Theo Avatar answered Oct 05 '22 22:10

Theo