In Rails application(Rails 6) I have created a directory in the root of rails application - outside of /app
folder. I want to try to keep some logic outside of Rails web framework.
- rails_root
- app/
- models/
- controllers/
- lib/
- tasks/
- my_domain/
- check_record.rb
check_record.rb file
module MyDomain
module CheckRecord
def self.call(record)
end
end
end
Now I am not able to autoload this directory in test(RSpec) and development (rails console) environments.
When I try in application.rb
config.autoload_paths += %W(#{config.root}/my_domain)
Tests fail because of uninitialized constant #Class:0x00007f96e1f1ad90::MyDomain
Receiving same error when try to access classes in rails console
When I try in application.rb
config.paths.add "my_domain", eager_load: true, glob: "**/*.rb"
I can see all files from that folder being registered in Rails.configuration.eager_load_paths
,
but tests fail with same error message
When I move this code to dedicated initializer class same output or when running Rails console initializer is not loaded at all.
Usage of the domain types:
class MyRecord < ApplicationRecord
def check
MyDomain::CheckRecord.call(self)
end
end
How I can eager- or auto- load directory with ruby files outside of /app
folder?
I believe you are using zeitwerk autoloader which is the default in Rails 6. In that case your check_record.rb file should be
And it should be called like this
Please refer https://guides.rubyonrails.org/autoloading_and_reloading_constants.html#project-structure for more details