@@ -83,33 +83,24 @@ def run_initializers
8383
8484 sig { void }
8585 def load_engines_in_zeitwerk_mode
86- autoloader = Rails . autoloaders . once
86+ # Collect all the directories that are already managed by all existing Zeitwerk loaders.
87+ managed_dirs = Zeitwerk ::Registry . loaders . flat_map ( &:dirs ) . to_set
88+ # We use a fresh loader to load the engine directories, so that we don't interfere with
89+ # any of the existing loaders.
90+ autoloader = Zeitwerk ::Loader . new
8791
88- # This is code adapted from various Rails application initializers in
89- # - https://github.com/rails/rails/blob/bba0db73c1e96f00d5da45f166ee6b0183ec254d/railties/lib/rails/application/bootstrap.rb#L81-L92
90- # - https://github.com/rails/rails/blob/bba0db73c1e96f00d5da45f166ee6b0183ec254d/railties/lib/rails/application/finisher.rb#L21-L40
91- # - https://github.com/rails/rails/blob/bba0db73c1e96f00d5da45f166ee6b0183ec254d/railties/lib/rails/application/finisher.rb#L74
92-
93- (
94- ActiveSupport ::Dependencies . autoload_once_paths +
95- ActiveSupport ::Dependencies . autoload_paths
96- ) . uniq . each do |path |
97- # Zeitwerk only accepts existing directories in `push_dir`.
98- next unless File . directory? ( path )
92+ engines . each do |engine |
93+ engine . config . eager_load_paths . each do |path |
94+ # Zeitwerk only accepts existing directories in `push_dir`.
95+ next unless File . directory? ( path )
96+ # We should not add directories that are already managed by a Zeitwerk loader.
97+ next if managed_dirs . member? ( path )
9998
100- autoloader . push_dir ( path )
99+ autoloader . push_dir ( path )
100+ end
101101 end
102102
103103 autoloader . setup
104-
105- # Unlike Rails code, we are not calling `Zeitwerk::Loader#eager_load_all` here because it will
106- # raise as soon as it encounters an error, which is not what we want. We want to try to eager load
107- # each loader independently, so that we can load as much as we can.
108- Zeitwerk ::Registry . loaders . each do |loader |
109- loader . eager_load
110- rescue
111- # This is fine, we eager load what can be eager loaded.
112- end
113104 end
114105
115106 sig { void }
0 commit comments