Tuesday, November 06, 2007

Rails: String#classify

Documentation
Create a class name from a table name like Rails does for table names to models. Note that this returns a string and not a Class. (To convert to an actual class follow classify with constantize.)

Examples
  • "egg_and_hams".classify #=> "EggAndHam"
  • "post".classify #=> "Post"
Usage
The classify method is helpful when metaprogramming. I generally replace "strings".singularize.camelize with "strings".classify (and the classify implementation calls singularize and camelize for me).

Test

require 'rubygems'
require 'active_support'
require 'test/unit'
require 'dust'

unit_tests do
test "singularize and camelize a string via classify" do
assert_equal "Name", "names".classify
end
end

No comments:

Post a Comment

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