Adding Custom Inflections in Rails with Zeitwerk

In the Rails ecosystem, we need to manage all sorts of naming conventions for classes, modules and related files. Rails uses an autoloading mechanism provided by the Zeitwerk gem to make this happen smoothly. In this article, we'll go into detail about customizing Rails autoloading by setting inflections - specifically, how to use capital letters in class and module names.

Getting started with inflections

In Rails, ActiveSupport::Inflector is the module that helps you inflect strings into different grammatical forms. For example, plural, singular, camel case, abbreviation, etc. Custom inflections are most commonly set in config/initializers/inflections.rb.
Inflections are a perfect solution when you need a specific abbreviation, rather than an exception to the rule that class and module names are camel case.
Let's define some global inflections:

# config/initializers/inflections.rb
ActiveSupport::Inflector.inflections() do |inflect|
  inflect.acronym 'REST'
  inflect.acronym 'API'
  inflect.acronym 'CSV'
  inflect.acronym 'SSL'
end

Note that from now on you'll need to refer to classes with these specific names when calling them. This means you can't use ApiClient or RestClient or CsvParser anymore - it has to be APIClient, RESTClient, CSVParser respectively in your codebase.
Using the specific string has it's advantage when exceptions need to be more concise. This is useful when only a few classes need to be inflected, rather than being declared globally as in the previous example. This can be done using a Zeitwerk inflector.

# config/initializers/zeitwerk.rb
Rails.autoloaders.each do |autoloader|
  autoloader.inflector = Zeitwerk::Inflector.new
  autoloader.inflector.inflect(
    "css_parser" => "CSSParser",
    "ssl_error" => "SSLError",
    "api" => "API",
  )
end

The autoloader.inflector.inflect() method maps specific filenames to class names. Now css_parser.rb will map to CSSParser, ssl_error.rb will map to SSLError, and api_client.rb will map to APIClient.
Remember that the inflection rules you declare in your initialization files are only executed once, during application initialization. Therefore, any changes you make to your inflection rules will require a server restart.

Conclusion

Rails autoloading, powered by Zeitwerk, allows you to effortlessly manage the naming conventions of your Ruby on Rails project and keep your codebase clean and simple. Custom inflections provide a convenient way to handle capitalization and abbreviations in class and module names. Take your Rails project to the next level by harnessing the power of custom inflections and making your eyes less cry during reading.

Have a great day!