Michael Anhari

How to use acronyms in the classes of your Rails application

A big pile of letter stamps

Sometimes you want to have an acronym in your codebase that you'd like to reference using all capital letters (i.e. CMS instead of Cms).

Unfortunately, Ruby will look for a class named Cms in a file named cms.rb and will tripped up if you try to name the class CMS.

Enter ActiveSupport::Inflector.

Letting Rails know about the acronyms in your codebase

Adding an acronym involves opening your config/initializers/inflections.rb initializer and using the acronym method.

ActiveSupport::Inflector.inflections(:en) do |inflect|
  inflect.acronym "CMS"
end

After restarting your server so that it picks up the new inflection, Rails will recognize CMS in app/models/cms.rb and you can use it when namespacing models as well (CMS::Article).

Newsletter

I'm working on sending out a weekly newsletter. I'll make it as easy as possible to unsubscribe at any time.