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
require 'rubygems'
require 'active_support'
require 'test/unit'
require 'dust'
unit_tests do
class Klass
end
test "constantize a string representation of a class" do
assert_equal Klass, "Klass".constantize
end
end
1 comment:
Much thanks for this. Searched for "rails string to class" and this was the first result! Very helpful.
Reply DeleteNote: Only a member of this blog may post a comment.
[フレーム]