Read more

Zeitwerk: How to collapse folders in Rails

Niklas Hä.
November 08, 2023Software engineer at makandra GmbH

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
Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show archive.org snapshot

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

Posted by Niklas Hä. to makandra dev (2023-11-08 13:54)