In Rails the pluralizations are managed by the Inflector class: it knows that the plural of “user” is “users”, but the plural of “person” is “people”. To add new inflection rules, one can add new rules in the environment.rb, but it is important to add the Inflector.inflections block after the Initializer.run block.

ActiveSupport::Inflector.inflections do |inflect|
 inflect.irregular 'criterion', 'criteria'
end

..which results in..

>> "Criterion".pluralize
=> "Criteria"
>> "Criteria".singularize
>> "Criterion"

A short overview of the name conversion functions:

  • camelize » the capitalized form of the word (“first letter uppercase”)
  • classify » the class name form for the word (“like Rails does for table names to models”)
  • foreign_key » converts to class name, downcase and adds “_id” suffix
  • humanize » Capitalizes the first word, turns underscores into spaces and strips “_id” suffix
  • pluralize » the plural form of the word
  • singularize » the singular form of the word
  • tableize » the table name for the word (“like Rails does for models to table names”)
  • titleize » the pretty title for the word (“capitalizes all the words and turns undescores into spaces”)
  • underscore » the underscored, lowercase form of the word (“the reverse of camelize.”)

Examples:

>> "ham_and_egg".humanize
>> "Ham and egg"

>> "ham_and_egg".classify
>> "HamAndEgg"

>> "ham_and_egg".foreign_key
>> "ham_and_egg_id"

see also: the pluralizer

About these ads