How do I call a class from a string containing that class name inside of it? (I guess I could do case/when but that seems ugly.)
The reason I ask is because I\'m us
"Object".constantize # => Object
I think what you want is constantize
That's an RoR construct. I don't know if there's one for ruby core
I know this is an old question but I just want to leave this note, it may be helpful for others.
In plain Ruby, Module.const_get can find nested constants. For instance, having the following structure:
module MyModule
module MySubmodule
class MyModel
end
end
end
You can use it as follows:
Module.const_get("MyModule::MySubmodule::MyModel")
MyModule.const_get("MySubmodule")
MyModule::MySubmodule.const_get("MyModel")
If you want to convert string to actuall class name to access model or any other class
str = "group class"
> str.camelize.constantize 'or'
> str.classify.constantize 'or'
> str.titleize.constantize
Example :
def call_me(str)
str.titleize.gsub(" ","").constantize.all
end
Call method : call_me("group class")
Result:
GroupClass Load (0.7ms) SELECT `group_classes`.* FROM `group_classes`
When ActiveSupport is available (e.g. in Rails): String#constantize or String#safe_constantize, that is "ClassName".constantize
.
In pure Ruby: Module#const_get, typically Object.const_get("ClassName")
.
In recent rubies, both work with constants nested in modules, like in Object.const_get("Outer::Inner")
.
Given a string, first call classify to create a class name (still a string), then call constantize to try to find and return the class name constant (note that class names are constants).
some_string.classify.constantize