Get a class by name in Ruby?

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).

Leave a Comment