Search code examples
ruby-on-railszeitwerk

Can't customize inflection (ID)


The controller:

# app/controllers/v1/nem_id_controller.rb
class V1::NemIDController < ApplicationController
end

I created an initializer to customize the inflection:

# config/initializers/zeitwerk.rb
Rails.autoloaders.each do |autoloader|
  autoloader.inflector = Zeitwerk::Inflector.new
  autoloader.inflector.inflect(
    "nem_id" => "NemID"
  )
end

The error:

expected file app/controllers/v1/nem_id_controller.rb to define constant V1::NemIdController

Inspired from: https://guides.rubyonrails.org/autoloading_and_reloading_constants.html#customizing-inflections

It does not work with inflection.acronym('ID') because it will cause this error: https://github.com/rails/rails/issues/40068


Solution

  • The overrides for Zeitwerk::Inflector are simpler than you're thinking. From the fine source code:

    def camelize(basename, _abspath)
      overrides[basename] || basename.split('_').each(&:capitalize!).join
    end
    

    The overrides are applied to whole components (i.e. nem_id_controller) or underscore-delimited components (i.d. nem, id, controller). You want to override the whole nem_id_controller:

    autoloader.inflector.inflect(
      'nem_id_controller' => 'NemIDController'
    )