Search code examples
ruby-on-railsrubyzeitwerk

Zeitwerk? Ruby on Rails ::Domains::Article => /app/domains/domains/ariticle.rb


I have domain logic code stored in

app/domains/domains/article.rb

The class is

class Domains::Article
end

It bothers me that the proper loading structure is app/domains/domains/article.rb and not app/domains/article.rb

Does anyone know what the proper directory structure and related autoload_path is?


Solution

  • I was able to solve this issue with the following initializer

    # config/initializers/autoloading.rb
    require 'zeitwerk'
    
    module Domains; end
    
    loader = Zeitwerk::Loader.new
    ActiveSupport::Dependencies.autoload_paths.delete("#{Rails.root}/app/domains")
    loader.push_dir("#{Rails.root}/app/domains", namespace: Domains)
    loader.setup
    

    ------------------UPDATE------------------

    I found a better solution. I was running into an issue where the files were not reloading on change. I was able to get the custom namespace working with the following:

    In config/application.rb, I added my directory path to autoload_paths:

    config.autoload_paths += ['app/lib', 'lib',  "#{Rails.root}/app/domains"]
    

    And in my initializer I changed to the following:

    require 'zeitwerk'
    
    module Domains; end
    
    Rails.autoloaders.main.push_dir("#{Rails.root}/app/domains", namespace: Domains)
    

    With this setup, I get my custom namespace and auto reloading when files are changed.