GOAL: To use a Rack middleware to reload the application whenever we change the source code.
At this point, we have a small problem.
If you make a change in your application, it won't be reflected in the browser. For this, you need to first
- Stop the server by pressing
ctrl + c
on the keyboard. - Make the change.
- Restart the server by running
rackup
orpuma
command.
As you can probably guess, it can get tedious to restart the server after every change.
Is there a better way?
Yes! The Rack gem ships with a Rack::Reloader
middleware that reloads the application after changing the source code.
A middleware is a small, focused, and reusable application that provides useful functionality to your main app.
Middleware sits between the user and the application code. When an HTTP request comes in, the middleware can intercept, examine, and modify it. Similarly, it can examine and modify the HTTP response before forwarding it to the user.
Check out my article on Rack middleware to learn more: Rails Middleware: (Almost) Everything You Need to Know
Use the Rack::Reloader Middleware
First, stop the running application by pressing ctrl+c
and then add the Rack::Reloader
middleware in the config.ru
file as follows:
require 'rack'
require_relative './app'
use Rack::Reloader, 0 # <- Add this line
run App.new
Now launch the web server using puma
command.
From now on, whenever you change the source code, the Reloader middleware will automatically reload the application when the next request arrives. So we don't have to restart the server manually.
Problem solved 👍