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:
- serve static files like stylesheets and images using the
Rack::Static
middleware, and - 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.
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.