1

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

David
  • 97
  • 9

2 Answers2

1

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'
)
mu is too short
  • 426,620
  • 70
  • 833
  • 800
1

From the official guide

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

If you want a common acronym to be recognized as such across all constants. You can set it as such:

# config/initializers/inflections.rb
ActiveSupport::Inflector.inflections(:en) do |inflect|
  inflect.acronym "CSV"
end

but Be careful, after you do this, you can't have mixed constants such as

CsvData and CSVPage

Pick your preference or otherwise, with the autoloader inflector, you can define both separately.

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

Mathieu J.
  • 1,932
  • 19
  • 29