0

I am upgrade ruby to ver 3.1.3, rails ver 6.1 And I got error NameError: uninitialized constant

My folder tree:

- app
 |- models
   |- area.rb
   |- area
     |- search.rb
     |- constants.rb

In search.rb

module Area::Search
 include do
  # some functions here
 end
end

In area.rb

class Area < ApplicationRecord
 include Area::Search

 # some method here
end

In ./config/application.rb I custom directories for autoloading config.autoload_paths += Dir["#{config.root}/app/models/**/"]

Then I run rails zeitwerk:check I get an error

NameError: uninitialized constant Area

module Area::Search
       ^^^^
Did you mean?  Arel

1 Answers1

0

This is a case of circular dependency.

Think about it this way, which file should be loaded first?

If it's search.rb, it will find Area::Search with Area undefined.

If it's area.rb, it will find include Area::Search with Area defined, but Search undefined.

Neiter file can be loaded without the other.

Change the definition of Area::Search to

class Area < ApplicationRecord
  module Search
    include do
      # some functions here
    end
  end
end

Or rename the namespace to something other than Area so it could be a module like Areas.

Or define the Search module inside the Area class in the area.rb file if they are tightly coupled.

Siim Liiser
  • 3,860
  • 11
  • 13