Skip to Content

Rails - Add configuration for Zeitwerk to get perfect namespaces

Posted on

This TIL came from Rails Viewcomponent Tips post.

By default, the Rails auto-loader - Zeitwerk will convert underscore_cased/ folder names into SentenceCased:: namespace.

But sometime, this is weird cause it’s what I want! For example, if I have a folder ui/, by default, Zeitwerk loads them under the Ui:: namespace, rather than UI::.

We can tweak with a custom Zeiwerk initializer in config/initializers/zeitwerk.rb

Rails.autoloaders.main.inflector.inflect("ui" => "UI")

So we can load class with a nice namespace. eg: UI::Button rather than Ui::Button, or FAQ instead of Faq.o

References

comments powered by Disqus