0

I'm having some trouble switching from the classic autoloader to Zeitwerk with a Rails app that's seen the light of day back in Rails 3 days – so there's some crust there.

Some model code has been extracted to modules and these modules are nested in the model class (which acts as the namespace):

# app/models/donation
class Donation < ApplicationRecord
  (...)
end

# app/models/donation/download
class Donation
  module Download
    def csv
      (...)
    end
  end
end

The modules are then used on the fly when needed:

donation = Donation.find(...)
donation.extend(Donation::Download).csv

Since the subdirs in app/models are not added by default, it's done explicitly in application.rb:

Dir[
  "#{config.root}/app/models/*/"
].then do |paths|
  config.autoload_paths += paths
  config.eager_load_paths += paths
end

The eager_load_paths are required by Zeitwerk (as per the Rails guides), however, Zeitwerk doesn't seem to like this constellation:

% rails zeitwerk:check
Hold on, I am eager loading the application.
expected file app/models/donation/download.rb to define constant Download

Strange, because Download is defined there. Any idea what's going on here and how best to refactor things to work with Zeitwerk?

Thanks for your hints!

svoop
  • 3,318
  • 1
  • 23
  • 41
  • 2
    I don't think you need those `autoload_paths` and `eager_load_paths`. I think you end up telling Zeitwerk that `app/models/donation` is a top-level directory rather than some nested, hence the complain about `Download` rather than `Donation::Download`. – mu is too short Feb 09 '22 at 23:07
  • Good point, makes total sense. I bump into another problem when I remove the explicit additions, but those are to be expected due to STI. Thanks, @muistooshort ! – svoop Feb 10 '22 at 07:58

1 Answers1

0

Hmmm, that should work out of the box, looks like a regular setup to me.

Since app/models is in the autoload paths, Donation and Donation::Download are going to be autoloaded just fine, no custom configuration is needed.

If they do not, the app has to be doing something funky. We could debug it.

Xavier Noria
  • 1,640
  • 1
  • 8
  • 10