Search code examples
ruby-on-railszeitwerk

Rails Zeitwerk not respecting class in a module


Running rails zeitwerk:check returns expected file app/api/mariana_tek_client.rb to define constant MarianaTekClient

The odd thing is that I have the following class defined in this file, which seems to follow the convention that I've seen documented: project/app/api/mariana_tek_client.rb

module Api
  class MarianaTekClient
    include HTTParty
  end
end

If I remove the module from the file and leave the class definition only, Zeitwerk stops failing, but this is contrary to what I've seen in all its docs. Plus, I want my namespace!

This works:

class MarianaTekClient
  include HTTParty
end

Would love if someone can clue me into why its failing with the namespace.


Solution

  • I'm guessing you've added app/api as an extra autoload path. If so, Zeitwerk will look in that folder for classes in the root namespace, and subfolders for classes in modules - so it expects app/api/mariana_tek_client.rb to contain MarianaTekClient; if you want Api::MarianaTekClient then that would need to go in app/api/api/mariana_tek_client.rb.

    You could point Zeitwerk at app, and it would then look for Api::MarianaTekClient in app/api/mariana_tek_client.rb; but that is discouraged and would probably cause you more problems in the long term.

    I'd recommend using the default Zeitwerk configuration, and putting your model classes under app/models; so it would then look for Api::MarianaTekClient in app/models/api/mariana_tek_client.rb - as would anyone else working on your code.