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

# 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 Article model, passing the title and body properties. Although they're hard-coded for now, we'll fetch them from the database in a future lesson.

# controllers/articles_controller.rb

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

class ArticlesController < ApplicationController
  def index
    @title = "Write Software, Well"
    @tagline = "Learn to program Ruby and build webapps with Rails"

    @article = Article.new "Rails Companion", "Let's build a web application in Ruby, without Rails!"
  end
end

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

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

<html>
  <head>
    <title>Application</title>
    <link rel="stylesheet" href="/public/style.css">
    <meta charset="utf-8">
  </head>

  <body>
    <main>
      <header>
        <h1>
          <%= @title %>
        </h1>
        <p>
          <%= @tagline %>
        </p>
      </header>

      <hr>

      <article>
        <h2>
          <%= @article.title %>
        </h2>
        <p>
          <%= @article.body %>
        </p>
      </article>
    </main>
  </body>
</html>

Launch the app, and you should see this page.

article.png

Now we could stop here, but all those require_relative 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.