WhatCodeCraves

Rails String Inflections

I've been using constantize to turn strings into Class objects. Constantize is mixed into the String class by Rails. This got me to thinking about other clever helpers that might be mixed into the string class. A quick search through the API did not disappoint.

In ActiveSupport::CoreExtensions::String::Inflections, I found a whole list of goodies. I can find the database table name for a given class with 'tableize'. If I just wanted a Class name string instead of a Class object, I can use 'classify'. 'dasherize' probably isn't too useful for me, but I thought it was cute. I can see 'demodulerize' and 'foreign_key' to be very useful. 'humanize', 'pluralize', 'titleize' could be really useful for manipulating text before it's rendered for the user. 'underscore' can be used to calculate paths to files based on their class names.

Here's a quick cheatsheet of all the methods.

methodbeforeafter
camelcase same as camelize
camelize i_like/them_camelsILike::ThemCamels
classify fish_and_chipsFishAndChip
constantize classify, then turns it into a class object
dasherize this_ones_cutethis-ones-cute
demodulize Strings::All::This::ClassClass
foreign_key Namespace::Modelmodel_id
humanize employee_salary_idEmployee salary
pluralize sheepsheep
singularize sheepsheep
tableize FrenchToastfrench_toasts
titlecase same as titleize
titleize good night moonGood Night Moon
underscore NameSpace::Modelname_space/model