Serving static files in Ruby

Serving Static Files in Ruby

This is the fourth article in the series where we build a simple, yet complete web app in plain Ruby, without using Rails to better understand how Rails works. In this article, we'll learn how to serve static files in plain Ruby, without using Rails.

7 min read

So far, we have created a simple-yet-complete web application in Ruby without using Rails with the support of routing and controllers. However, we are still rendering the contents of the view from our controller classes. For example:

class ArticlesController < ApplicationController
  def index
    '<h1>All Articles</h1>'
  end
end

In this post, we will improve our code and make it more Rails-like with the following enhancements:

  1. serve static files like stylesheets and images using the Rack::Static middleware, and
  2. separate the views from the application logic

By the end, you'll have a pretty good understanding of how to serve static files using a middleware in Ruby.


Separation of Concerns

As things stand now, our application mixes the logic and the views together in a single file. Although there's no custom 'application logic' here, you can see the response HTML with h1 tags mixed in the Ruby script.

This is 'generally' not considered good practice in software development, as it tightly couples the logic and view together (however, some folks (see: React) may have differing opinions). You can't change one of them without understanding or affecting the other.

Although it works, it's a good idea to separate the view from the controller. That way, we don't have to change the controller classes when the view needs to be updated, and vice-versa. Both the controller and view can evolve independently.

Hence, the first thing we'll do is separate the application logic and the views. The benefit is that you can change the view without worrying about the logic, and also change the logic without affecting the views.

💡
You might have heard of the separation of concerns principle. This is what it means in the simplest form.

Separate View from Application

We will separate the view from the application logic by moving the response HTML out of the app.rb to a file named index.html under a newly created views directory, just like Rails.