Reputation: 1662
I have a specific app folder in my lib/ which contains everything that is not relevant to rails. This is the structure :
lib/
|myapp/
|repositories/
|repo1.rb
|repo2.rb
|use_cases/
|use_case1.rb
|use_case2.rb
I added the lib folder in my autoload_path like this :
config.autoload_paths += Dir["#{config.root}/lib/**/"]
If I want to use UseCase1 in one of my controllers I have to specify the full path :
MyApp::UseCases::UseCase1.new
Same thing for repositories.
Is there a way to require it globally so as I can only use UseCase1.new in my controllers ?
Upvotes: 3
Views: 3552
Reputation: 62638
Requiring and including are different. Requiring is the process of loading the file and (making MyApp::UseCases::UseCase1
available), whereas include
will mix a module into the current module; this has the effect of making its constants available in the current context, as well.
In an initializer, try explicitly requiring your files:
require File.join(Rails.root, "lib", "myapp", "use_cases", "use_case1.rb")
require File.join(Rails.root, "lib", "myapp", "use_cases", "use_case2.rb")
Then include the module containing your classes:
include MyApp::UseCases
This should make all the constants under UseCases
available for lookup in the current scope, which in the case of an initializer will be the main
scope, making those constants effectively available everywhere.
Upvotes: 7