Rails String Inflections

11 Jul 2018
.humanize

Here is a quick cheat sheet of the Rails string inflector methods. There are more but these are all the methods that end in ize which are the string transformers.

Camelize

'stuart_yamartino'.camelize # => 'StuartYamartino'
'stuart_yamartino'.camelize(:lower) # => 'stuartYamartino'
'account/profile_controller'.camelize # => 'Account::ProfileController'

Constantize

'Module'.constantize # => Module (note it returns an actual constant)

Dasherize

'stuart_yamartino'.dasherize # => 'stuart-yamartino'

Demodulize + Deconstantize

'Account::ProfileController'.demodulize # => 'ProfileController'
'Account::ProfileController'.deconstantize # => 'Account'

Humanize + Titleize

'tacos_for_breakfast'.humanize # => 'Tacos for breakfast'
'tacos_for_breakfast'.titleize # => 'Tacos For Breakfast'

Parameterize

'This is for a url.'.parameterize # => 'this-is-for-a-url'

Pluralize + Singularize

'taco'.pluralize # => 'tacos'
'octopus'.pluralize # => 'octopi'

'tacos'.singularize # => 'taco'
'octopi'.singularize # => 'octopus'

Tableize

Get the corresponding table name for a model.

'AdminUser'.tableize # => 'admin_users'
Improvements, bugs, typos? Contribute on GitHub ❤️