How to ignore a folder in Zeitwerk for Rails 6?
Asked Answered
T

3

19

Simple question, but somehow the answer escapes me.

In moving to Rails 6 with Zeitwerk, I get:

Please, check the "Autoloading and Reloading Constants" guide for solutions.
 (called from <top (required)> at APP_ROOT/config/environment.rb:7)
rails aborted!
Zeitwerk::NameError: wrong constant name Enforce-calls-to-come-from-aws inferred by Module from directory

  APP_ROOT/app/junkyard/enforce-calls-to-come-from-aws

Possible ways to address this:

  * Tell Zeitwerk to ignore this particular directory.
  * Tell Zeitwerk to ignore one of its parent directories.
  * Rename the directory to comply with the naming conventions.

Which seems great: that's a junk folder and should never be loaded, so ignoring it makes perfect sense.

The Zeitwerk docs at https://github.com/fxn/zeitwerk say

tests = "#{__dir__}/**/*_test.rb"
loader.ignore(tests)
loader.setup

is how you ignore a folder. Fair enough. But how do I find loader? The Rails guide on Zeitwerk autoloading (https://guides.rubyonrails.org/autoloading_and_reloading_constants.html) doesn't mention how to ignore folders directly, but does mention the autoloader stashed at Rails.autoloaders.main, so I figured that

Rails.autoloaders.main.ignore("#{__dir__}/junkyard/**/*.rb")

or

Rails.autoloaders.main.ignore("#{__dir__}/app/junkyard/**/*.rb")

would be the way to go. No luck. I've tried putting this in application.rb and in initializers/zeitwerk.rb and neither worked.

Any ideas where and how to ignore a folder with Zeitwerk within Rails?

PS: yes, I know I should just remove this from app, and I will. But the question still vexes.

Trochaic answered 26/9, 2019 at 23:21 Comment(0)
T
44

I ran into this same issue, and it turns out it was complaining about a folder name.

Adding this to application.rb may work for you:

Rails.autoloaders.main.ignore(Rails.root.join('app/junkyard'))

Tetrapterous answered 1/10, 2019 at 13:24 Comment(4)
Thanks @ajkerr, that helps!Trochaic
Thanks for this! It worked for me to put this in an initializer which felt better than application.rb.Uniliteral
@IainBryson you should accept this answer if it solved your problemTransliterate
Wonder if this is still the way to go with Rails 7.1 ?Maim
S
9

I added this to config/initializers/zeitwerk.rb:

Rails.autoloaders.each do |autoloader|
  autoloader.ignore(Rails.root.join('app/ui'))
...
Stichous answered 4/4, 2022 at 19:31 Comment(0)
C
0

A lazy way of ignoring a directory, is to name with with a full-stop (period).

.folder_to_be_ignored

Zeitwerk ignores automatically any file or directory whose name starts with a dot, and any files that do not have the extension ".rb". Source

Circumference answered 14/3 at 1:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.