Saturday, November 03, 2007

Rails: String#camelize

By default, camelize converts strings to UpperCamelCase. If the argument to camelize is set to ":lower" then camelize produces lowerCamelCase.

camelize will also convert ’/’ to ’::’ which is useful for converting paths to namespaces

  • "active_record".camelize #=> "ActiveRecord"
  • "active_record".camelize(:lower) #=> "activeRecord"
  • "active_record/errors".camelize #=> "ActiveRecord::Errors"
  • "active_record/errors".camelize(:lower) #=> "activeRecord::Errors"
I generally use camelize when metaprogrammming to convert from a underscored version of a class name.


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

unit_tests do
test "change underscored word to camelized word" do
assert_equal "AClassName", "a_class_name".camelize

1 comment:

  1. There's another use case which is kind of obscure but also kind of ironic - requiring ActiveSupport itself.

    If you

    require "active_support"

    Ruby or Rails runs off and tries to do this method called activate. So say you're using ActiveSupport in your .irbrc, to get all those goodies when you write Ruby interactively, and when you write Rails interactively in the console. If you do that in a Rails install which keeps its ActiveSupport in vendor/rails, which happens from time to time, it gets confused and tries to call activate twice. and this, for some reason, kills the whole .irbrc load process.

    The easy way around this is:

    require "active_support" unless defined? ActiveSupport

    But if you're doing a lot of requires in your .irbrc, and you don't want to deal with **any** instance of that particular class of error, you might do something like this:

    %w{net/http active_support}.each {|lib| require lib unless defined? lib.camelize}

    of course that requires extracting and copying the method before going to the library, so it's kind of messy. but it is a use case.


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