Constantize tries to find a declared constant with the name specified in the string. It raises a NameError when the name is not in CamelCase or is not initialized.Usage
Examples
- "Module".constantize #=> Module
- "Class".constantize #=> Class
Constantize is definitely the most used String method that I utilize while metaprogramming.
Test
unit_tests do
end
test "constantize a string representation of a class" do
assert_equal Klass, "Klass".constantize
end
end
Much thanks for this. Searched for "rails string to class" and this was the first result! Very helpful.
ReplyDelete