Last Updated: February 25, 2016
·
771
· esbanarango

From a string containing a class name to a Real Class Object

Doing the same action on multiple clases.

Some days ago I was needing to make a change on several models in rails, those models had the same attribute that I wanted to changed on each of them, so to do it I used the Kernel.const_get() method. To convert the string name of the classes into a real clases itself.

"All the built-in classes, along with the classes you define, have a corresponding global constant with the same name as the class." http://www.ruby-doc.org/

["Model1","Model2","Model3","Model4"].each do |t|
  klass = Kernel.const_get(t)
  if klass.is_a?(Class) #To be sure
   #Now here you can use this Class normaly
   klass.method_x 
  end
end

2 Responses
Add your response

Why jump through hoops with reassignment instead of if klass.is_a?(Class)

over 1 year ago ·

@richoh You're right; I just wanted to 'clarify' that it could not be a Class

over 1 year ago ·