Search code examples
ruby-on-railszeitwerk

Zeitwerk collapse namespacing to root level


Zeitwerk's readme gives this example for collapsing namespaces:

booking.rb -> Booking

booking/actions/create.rb -> Booking::Create

To make it work that way, configure Zeitwerk to collapse said directory:

loader.collapse("#{__dir__}/booking/actions")

But I don't want to cut out the middle, I want to bring everything to root level namespacing.

I.e. instead of Booking::Actions::Create or Booking::Create I just want Create. How do I do this?


Solution

  • collapse just removes the last directory in the path given, so if you want to remove two directories, run collapse for each directory.

    E.g.

    If you have /app/a/b/c/d.rb then you can bring d.rb up to no namespacing with:

    loader.collapse("app/a/b/c")
    loader.collapse("app/a/b")
    

    Zeitwerk will look at d.rb as if it's within app/a/, and all subfolders of app/ are considered root level