To load all the dependencies like classes and modules without explicitly requiring them, we'll use Zeitwerk. In the weby
directory, run the following command:
$ bundle add zeitwerk
Next, require the gem in the app.rb
file.
# app.rb
require 'zeitwerk'
Finally, in the application constructor, add the directories where you want to look for constants. I'll add the models
and controllers
directories, so that Zeitwerk loads the model and controller classes automatically.
# app.rb
class App
def initialize
@logger = Logger.new("log/development.log")
loader = Zeitwerk::Loader.new
loader.push_dir('models')
loader.push_dir('controllers')
loader.setup
end
end
P.S. The push_dir
method pushes the directory to the list of root directories.
Now, remove the require_relative
statements from the articles_controller.rb
and router.rb
file that load controllers and models.
Restart the application, and everything works just fine.
Out of the box, Zeitwerk uses String#camelize
naming conventions for file names. For example, it expects that a class named UsersController
is defined in a file named users_controller.rb
, because:
"users_controller".camelize # => UsersController