Zeitwerk: How to collapse folders in Rails

Updated . Posted . Visible to the public. Repeats.

All direct child directories of app are automatically added to the eager- and autoload paths. They do NOT create a module for namespacing. This is intuitive, since there normally is no module Model, or module Controller. If you want to add a new base directory, there's no additional config needed.

Example

app
├── controllers
├── helpers
├── inputs # No config needed 
├── mailers
├── models
├── uploaders # No config needed
├── util # No config needed
└── workers # No config needed

Sometimes it's handy to group files within a directory, but not reflect that grouping within the Ruby module structure. The typical example would be the concerns folder, which exists in new Rails applications by default and does not create a constant module Concerns.

app
├── models
    ├── concerns
        ├── shareable.rb # Defines constant Shareable, not Concerns::Shareable

If you want to collapse your own directories, you can do so with the following official api:

app
├── models
    ├── shared
        ├── shareable.rb # Defines constant Shared::Shareable

# e.g. in application.rb
Rails.autoloaders.main.collapse("#{Rails.root}/app/models/shared")

# with collapsed shared dir
app
├── models
    ├── shared
        ├── shareable.rb # Defines constant Shareable

Niklas Hä.
Last edit
Michael Leimstädtner
License
Source code in this card is licensed under the MIT License.
Posted by Niklas Hä. to makandra dev (2023-11-08 12:54)