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 >
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.
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.
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".
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With