Ever run into issues with strings? Problems like converting CamelCase to snake_case, pluralizing words, or making integers into ordinals? Inflectors give us an easy solution.
An ‘inflector’ is anything that applies ‘inflection’, from Latin for ‘bending’, meaning that it can bend strings. Conveniently, Rails provides a number of inflectors in the ActiveSupport::Inflector module. The entire ActiveSupport component to Rails is handy; this RailsGuide is worth a read. That said, this post is a quick primer on the inflector methods in Rails.
Set-up
Because ActiveSupport is a Ruby on Rails component, the ActiveSupport::Inflector will be available by default in Rails applications.1
To use it outside a Rails app (in irb, for example), run: require ‘active_support/inflector’. It’s that simple.
Examples
Pluralize and Singularize
These two methods, inverses of each other, adjust the pluralization of nouns.
1 2 3 4 5 6 7 8 9 10 11 | |
Note: pluralize can be passed an integer as an optional argument, which pluralizes the string unless the argument is 1.
Camelize and Underscore
Another set of two inverses, camelize and underscore assist in formatting strings (names of methods vs. classes, for example).
1 2 3 4 5 6 | |
Note: camelize can be passed the optional argument :lower to make the first letter lowercase.
Assorted others
There are a lot of other helpful inflector methods, all of which are detailed in Rails documentation. A quick definition of the others:
titleize: capitalizes each word of the receiver string.dasherize: replaces underscores with dashes.demodulize: given a qualified constant name (“ActiveSupport::Inflector”), it returns the constant name, the rightmost part (“Inflector”).deconstantize: likedemodulize, but removes the righmost part (i.e.,“ActiveSupport::Inflector”to“ActiveSupport”.constantize: resolves the constant reference, or raisesNameErrorif no such constant has been initialized.parameterize: normalizes the receiver for use in urls.tableize:underscorefollowed by pluralize, for use in naming tables.classify: inverse oftableize, returns singularized and camelized.humanize: replaces underscores with spaces, removes “_id” suffixes, and capitalizes first word.foreign_key: gives a foreign key column name from a class name.
Hopefully this was helpful, if for no other reason than a quick reference or refresher on inflectors and/or to point you towards the ActiveSupport guide and key inflector methods.
-
The exception to this default is when
config.active_support.bareis set to true in a Rails application.↩
