When a request for style.css arrives, we want to serve the contents of the style.css file. Additionally, we want to serve style.css as it is, without inserting any dynamic content to it.

The Rack::Static middleware lets us accomplish this exact use case.

According to the documentation,

The Rack::Static middleware intercepts requests for static files (javascript files, images, stylesheets, etc) based on the url prefixes or route mappings passed in the options, and serves them using a Rack::Files object. This allows a Rack stack to serve both static and dynamic content.

Let's update the config.ru file to include the Rack::Static middleware.

require 'rack'
require_relative './app'

# Reload source after change
use Rack::Reloader, 0

# Serve all requests beginning with /public 
# from the "public" folder 
use Rack::Static, urls: ['/public']

run App.new

This tells the static middleware to serve all requests beginning with /public from the "public" directory.

That's it. Nothing needs to change in either the app.rb file or our controller.

Now restart the Puma server and reload the page. You can verify in the DevTools that our application sends the correct CSS this time, and our styles are getting applied. The favicon image is also getting loaded as expected 😃

static-favicon.png

How Rack::Static Middleware Works?

First, it intercepts the incoming HTTP request before it even hits our application.

Next, it checks the request path to see if it matches the pre-configured pattern, i.e. /public.

Finally, it serves the required file from this directory.

Our application remains blissfully unaware that a request for a static file was even made.

Pretty cool!

As of now, our view is a static HTML. That means each time the page loads, our application renders the same HTML, no matter what.

We want a dynamic view, i.e., a view that can embed variables in it, to render a different page each time you reload the browser. For this, we'll need a view template.

In the next lesson, we will learn how to use Rails-like dynamic views using the ERB gem.