# Using Zeitwerk Outside Rails

*Published on August 12, 2023*

---


> First things first:&nbsp;**it's Zeitwerk, not Zeitwork**. For some reason, I always thought it was Zeitwork. It was only when I tried to install the gem I noticed the typo. Luckily, there's no such gem called Zeitwork.

This is the next post in the series on&nbsp;building a web application in Ruby without Rails, where we'll use the Zeitwerk gem to load our dependencies without explicitly requiring them.

In Rails, you don't have to require classes and modules in advance. Somehow, they're just available to use right when you need them. This is all thanks to Zeitwerk, which is written by&nbsp;[Xavier Noria](https://hashref.com/), member of the Rails core team.

Now, you can enjoy the benefits of Zeitwerk without really understanding what it is or how it works, but it's good to know how to use it outside Rails to get the benefits it provides in your Ruby projects. For example, the new&nbsp;[mrsk](https://github.com/mrsked/mrsk/blob/main/mrsk.gemspec#L20)&nbsp;gem uses Zeitwerk internally to load its dependencies.

**Note:**&nbsp;In a future article that's fully dedicated to Zeitwerk, we'll try to figure out how it&nbsp;_**really**_&nbsp;works by reading the source code. This article only shows how to use it outside Rails.

**Here's the list of topics we'll cover in this article:**

- Introducing models to our no-rails app
- Using Zeitwerk to load classes and modules
- Bonus: How Rails Configures Zeitwerk

Before digging into Zeitwerk, let's first try to understand the problem it's solving. We'll do this by introducing the concept of models in our Ruby web application and then loading them with Zeitwerk.

> If you haven't been following the&nbsp;rails-companion&nbsp;series where we build a web application in Ruby without using Rails, the following code won't make much sense, but bear with me. It's very simple Ruby code, and we'll get to Zeitwerk very soon. Or you can directly jump to the&nbsp;[Zeitwerk](/using-zeitwerk-outside-rails#using-zeitwerk-to-load-constants-classes-and-modules)&nbsp;section.

Let's revisit the controller class we added in the&nbsp;[previous article on controllers](/implement-rails-controllers-in-ruby).

```ruby
# controllers/articles_controller.rb

require_relative 'application_controller'

class ArticlesController < ApplicationController
  def index
    @title = 'All Articles'
  end
end
```

The&nbsp;`@title`&nbsp;instance variable is accessed in the ERB view as follows:

```html
<%# views/articles/index.html.erb %>

<h1>
  <%= @title %>
</h1>
```

This works fine, but as the data we want to display gets complicated in size and shape, it doesn't make sense to store it in separate variables. For example, suppose we want to display a post, with its title and body. With separate variables, you might write this:

```ruby
# controllers/articles_controller.rb

require_relative 'application_controller'

class ArticlesController < ApplicationController
  def index
    @title = 'All Articles'
    
    @post_title = 'post title'
    @post_body  = 'post body'
  end
end
```

A better way to organize this data is to group the related variables together and encapsulate them inside proper Ruby objects, also called&nbsp;**models**&nbsp;in the Rails. For example, the above properties could be moved to a&nbsp;`Post`&nbsp;class.

The benefit of models is that you can move the common operations on the data to the objects methods, and it keeps your controllers nice and clean. Models also provide a place to keep all your business logic together, separate from the view or controller's logic.

## Introducing Models to Our No-Rails App

Let's create a new model called&nbsp;`Article`, which is just a plain Ruby class. For this, we'll first create a new directory&nbsp;`weby/models`&nbsp;and add a&nbsp;`article.rb`&nbsp;file in it.

```ruby
# models/article.rb

class Article
  attr_reader :title, :body

  def initialize(title, body)
    @title = title
    @body = body
  end
end
```

Next, I'll update the controller so it creates an instance of&nbsp;`Article`&nbsp;model, passing the `title` and `body` properties. Although they're hard-coded for now,&nbsp;**we'll fetch them from the database in a future post**.

```ruby
# controllers/articles_controller.rb

require_relative 'application_controller'
require_relative '../models/article'

class ArticlesController < ApplicationController
  def index
    @title = 'All Articles'
    @article = Article.new 'Ruby no Rails', 'Let\'s build a web application in Ruby, without Rails!'
  end
end
```

Finally, update the&nbsp;`index.html.erb`&nbsp;template to display the article's title and body. Since the `@article`&nbsp;object is included in the current binding, the template can access it without any problem.

```html
<%# views/articles/index.html.erb %>

<main>
  <h1 style="text-align: center;">
    <%= @title %>
  </h1>
  <div>
    <h3>
      <%= @article.title %>
    </h3>
    <p>
      <%= @article.body %>
    </p>
  </div>
</main>
```

Launch the app, and you should see this page.

![home.png](https://writesoftwarewell.com/media/4gnzfrpx7kvft82xysxfdc5hcfbb.png "All articles")

Now we could stop here, but all those&nbsp;`require_relative`&nbsp;statements are bugging me. Wouldn't it be nice if we could just use a class or module name, and our app would load it automatically?

This is where Zeitwerk enters the picture. Let's use Zeitwerk to autoload the constants and get rid of all the require statements.

## Using Zeitwerk to Load Constants (Classes and Modules)

To load all the dependencies like classes and modules without explicitly requiring them, we'll use Zeitwerk. In the&nbsp;`weby`&nbsp;directory, run the following command:

```bash
bundle add zeitwerk
```

Next, require the gem in the&nbsp;`app.rb`&nbsp;file.

```ruby
# app.rb

require 'zeitwerk'
```

Finally, in the application constructor, add the directories where you want to look for constants. I'll add the&nbsp;`models`&nbsp;and&nbsp;`controllers`&nbsp;directories, so that Zeitwerk loads the model and controller classes automatically.

```ruby
# app.rb

class App
  def initialize
    loader = Zeitwerk::Loader.new
    loader.push_dir('models')
    loader.push_dir('controllers')
    loader.setup
  end
end
```

P.S. The&nbsp;`push_dir`&nbsp;method pushes the directory to the list of root directories.

Now, remove the&nbsp;`require_relative`&nbsp;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&nbsp;`String#camelize`&nbsp;naming conventions for file names. For example, it expects that a class named&nbsp;`UsersController`&nbsp;is defined in a file named&nbsp;`users_controller.rb`, because:

```ruby
"users_controller".camelize # => UsersController
```

💡 Find the source code for this post on&nbsp;[GitHub](https://github.com/akshayKhot/weby/tree/models), in the&nbsp;`models`&nbsp;branch.

## How Rails Configures Zeitwerk

If you're curious how Rails uses and configures Zeitwerk, here's a highly simplified version of the Rails codebase that does what we just did.

The&nbsp;`Autoloaders`&nbsp;class sets up a Zeitwerk loader. The autoload paths are managed by the `Rails.autoloaders.main`&nbsp;autoloader.

```ruby
# railties/lib/rails/autoloaders.rb

module Rails
  class Autoloaders
    def initialize
      require "zeitwerk"

      @main = Zeitwerk::Loader.new
    end
  end
end
```

The Finisher module adds an&nbsp;[initializer](/introduction-to-rails-initializers)&nbsp;that adds the configured directories to the Zeitwerk loader.

```ruby
# railties/lib/rails/application/finisher.rb

module Rails
  class Application
    module Finisher
      initializer :setup_main_autoloader do
        autoloader = Rails.autoloaders.main
        
        autoload_paths.uniq.each do |path|
          autoloader.push_dir(path)
        end
        
        autoloader.setup
      end
    end
  end
end
```

Don't worry if it doesn't make sense. It was just a taste of what's to come. In a future post, we'll do a deep-dive into the Zeitwerk codebase to learn how it works, and also explore the Rails codebase to understand how it integrates Zeitwerk.

