Wednesday, November 07, 2007

Rails: String#constantize

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

Examples
  • "Module".constantize #=> Module
  • "Class".constantize #=> Class
Usage
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:

  1. Anonymous8:23 PM

    Much thanks for this. Searched for "rails string to class" and this was the first result! Very helpful.

    ReplyDelete

Note: Only a member of this blog may post a comment.