10.3 Layouts
At this point, our app is looking pretty good, but there are two significant blemishes: The HTML code for the three pages is highly repetitive, and navigating by hand from page to page is rather cumbersome. We’ll fix the first blemish in this section, and the second in Section 10.4. (And of course our app doesn’t yet detect palindromes, which is the subject of Section 10.5.)
If you followed Learn Enough CSS & Layout to Be Dangerous, you’ll know that the Layout in the title referred to page layout generally—using Cascading Style Sheets to move elements around on the page, align them properly, etc.— but we also saw that doing this properly requires defining layout templates that capture common patterns and eliminate duplication.
In the present case, each of our site’s pages has the same basic structure, as shown in Listing 10.10.
Listing 10.10: The HTML structure of our site’s pages.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Learn Enough Ruby Sample App</title> <link rel="stylesheet" type="text/css" href="/stylesheets/main.css"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400" rel="stylesheet"> </head> <body> <a href="/" class="header-logo"> <img src="/images/logo_b.png" alt="Learn Enough logo"> </a> <div class="container"> <div class="content"> <!-- page-specific content --> </div> </div> </body> </html>
Everything except the page-specific content (indicated by the highlighted HTML comment) is the same on each page. In Learn Enough CSS & Layout to Be Dangerous, we eliminated this duplication using Jekyll templates; in this tutorial, we’ll use Sinatra layouts instead.
Now, our site is currently working, in the sense that each page has the proper content at this stage of development. We’re about to make a change that involves moving around and deleting a bunch of HTML, and we’d like to do this without breaking the site. Does that sound like something we’ve seen before?
It does indeed. This is exactly the kind of problem we faced in Chapter 8 when we developed and then refactored the palindrome gem. In that case, we wrote automated tests to catch any regressions, and in this case we’re going to do the same. (I started making websites long before automated testing of web applications was possible, much less the norm, and believe me, automated tests are a huge improvement over testing web apps by hand.)
To get started, we’ll add some more gems to our Gemfile, this time in a group called :test that indicates gems that are needed only for tests. The result appears in Listing 10.11.
Listing 10.11: Adding gems for testing.
Gemfile
source 'https://rubygems.org' ruby '3.1.1' # Change this line if you're using a different Ruby version. gem 'sinatra', '2.2.0' gem 'puma', '5.6.4' gem 'rerun', '0.13.1' group :test do gem 'minitest', '5.15.0' gem 'minitest-reporters', '1.5.0' gem 'rack-test', '1.1.0' gem 'rake', '13.0.6' gem 'nokogiri', '1.13.3' end
We then install the gems as usual:
If you encounter an error while installing nokogiri (which is unfortunately common), you’ll have to apply your technical sophistication (Box 1.1) to resolve the issue; I especially recommend the “Google the error message” algorithm for this case.
We’ll factor out common elements needed in all tests into a test helper file, while also creating a file for our initial site pages tests:
The test helper requires all the necessary gems, and also includes the app itself using require_relative, which requires files relative to the current directory. The result appears in Listing 10.12.
Listing 10.12: The initial test helper.
test/test_helper.rb
ENV['RACK_ENV'] = 'test' require_relative '../app' require 'rack/test' require 'nokogiri' require 'minitest/autorun' require 'minitest/reporters' Minitest::Reporters.use!
We then need to create a Rakefile to tell the rake utility how to run the tests:
The contents are shown in Listing 10.13.
Listing 10.13: Configuring rake to run tests.
Rakefile
require 'rake/testtask'
We’ll put the result of Listing 10.13 to good use in a moment, but first we need to write some tests. We’ll start with super-basic tests so that the app serves up something, as indicated by the HTTP response code 200 (OK), which we can do like this:
Here we use the get command in the test to issue a GET request to the root URL /, which automatically creates an object called last_response as a side effect. We can then use a minitest assertion (Section 8.2) using the boolean method ok?, which is also available automatically. The result is a test that makes sure the server responded properly to the request.
Applying the above discussion to the About and Palindrome Detector pages as well, and combining them with configuration code pulled right from the official Sinatra documentation on tests, we arrive at our initial test suite, shown in Listing 10.14.
Listing 10.14: Our initial test suite. GREEN
test/site_pages_test.rb
require_relative 'test_helper' class PalindromeAppTest < Minitest::Test include Rack::Test::Methods def app Sinatra::Application end def test_index get '/' assert last_response.ok? end def test_about get '/about' assert last_response.ok? end def test_palindrome get '/palindrome' assert last_response.ok? end end
With the setup in Listing 10.13, we can use rake to execute the test suite as follows:
Listing 10.15: GREEN
$ bundle exec rake test 3 tests, 3 assertions, 0 failures, 0 errors, 0 skips
Also note that Listing 10.13 has followed the common Ruby convention of making running the test suite the default (an indication of how important tests are in the Ruby community), so we can actually just run rake by itself:3
Listing 10.16: GREEN
$ bundle exec rake 3 tests, 3 assertions, 0 failures, 0 errors, 0 skips
We’ll continue to use rake test for clarity, but it’s good to know about this alternative convention.
The tests in Listing 10.14 are a fine start, but they really only check if the pages are there at all. It would be nice to have a slightly more stringent test of the HTML content, though not too stringent—we don’t want our tests to make it hard to make changes in the future. As a middle ground, we’ll check that each page in the site has an h1 tag somewhere in the document.
In order to do this, we’ll write a short function in test_helper.rb to return a doc object, akin to the document object in JavaScript. We actually already know pretty much how to make it based on our work in Section 9.3, where we saw how to use Nokogiri to create a document from HTML, like this:
The only extra ingredient is the knowledge that Sinatra’s HTTP response objects always have a body attribute representing the HTML body (the full page, not just the body tag). This means we can define doc as shown in Listing 10.17.
Listing 10.17: What’s up, Doc?
test/test_helper.rb
ENV['RACK_ENV'] = 'test' require_relative '../app' require 'rack/test' require 'nokogiri' require 'minitest/autorun' require 'minitest/reporters' Minitest::Reporters.use! # Returns the document. def doc(response) Nokogiri::HTML(response.body) end
Now we’re ready to use doc to find the h1 (if any) on the page. One possibility would be to use doc.css as in, e.g., Listing 9.12:
In the present case, though, we only need to see if there’s any h1 tag, so we only need the first element:
This would work fine, but this is such a common case that Nokogiri has a special method for it, called at_css:
Because this will be nil if there’s no h1 and non-nil otherwise, we can use a simple assertion, like this:
Adding this to each page in our site yields the updated test suite shown in Listing 10.18.
Listing 10.18: Adding assertions for the presence of an h1 tag. GREEN
test/site_pages_test.rb
require_relative 'test_helper' class PalindromeAppTest < Minitest::Test include Rack::Test::Methods def app Sinatra::Application end def test_index get '/' assert last_response.ok? assert doc(last_response).at_css('h1') end def test_about get '/about' assert last_response.ok? assert doc(last_response).at_css('h1') end def test_palindrome get '/palindrome' assert last_response.ok? assert doc(last_response).at_css('h1') end end
By the way, some programmers adopt the convention of only ever having one assertion per test, whereas in Listing 10.18 we have two. In my experience, the overhead associated with setting up the right state (e.g., duplicating the calls to get) makes this convention inconvenient, and I’ve never run into any trouble from including multiple assertions in a test.
The tests in Listing 10.18 should now be GREEN as required:
Listing 10.19: GREEN
$ bundle exec rake test 3 tests, 6 assertions, 0 failures, 0 errors, 0 skips
At this point, we’re ready to use a Sinatra layout to eliminate duplication. Our first step is to remove the extraneous material from our pages, leaving only the core content, as shown in Listing 10.20, Listing 10.21, and Listing 10.22. (This is why the body content wasn’t fully indented before.)
Listing 10.20: The core Home (index) view.
views/index.erb
<h1>Sample Sinatra App</h1> <p> This is the sample Sinatra app for <a href="https://www.learnenough.com/ruby-tutorial"><em>Learn Enough Ruby to Be Dangerous</em></a>. Learn more on the <a href="/about">About</a> page. </p> <p> Click the <a href="https://en.wikipedia.org/wiki/Sator_Square">Sator Square</a> below to run the custom <a href="/palindrome">Palindrome Detector</a>. </p> <a class="sator-square" href="/palindrome"> <img src="/images/sator_square.jpg" alt="Sator Square"> </a>
Listing 10.21: The core About view.
views/about.erb
<h1>About</h1> <p> This site is the final application in <a href="https://www.learnenough.com/ruby-tutorial"><em>Learn Enough Ruby to Be Dangerous</em></a> by <a href="https://www.michaelhartl.com/">Michael Hartl</a>, a tutorial introduction to the <a href="https://www.ruby-lang.org/en/">Ruby programming language</a> that is part of <a href="https://www.learnenough.com/">LearnEnough.com</a>. </p> <p> <em>Learn Enough Ruby to Be Dangerous</em> is a natural prerequisite to the <a href="https://www.railstutorial.org/"><em>Ruby on Rails Tutorial</em></a>, a book and video series that is one of the leading introductions to web development. <em>Learn Enough Ruby</em> is also an excellent choice <em>after</em> the <em>Rails Tutorial</em> for those who prefer to start with the latter first. </p>
Listing 10.22: The core Palindrome Detector view.
views/palindrome.erb
<h1>Palindrome Detector</h1> <p>This will be the palindrome detector.</p>
Having stripped all the layout material from our pages, we’ll now create a file called layout.erb in the views directory that restores it:
Let’s start by filling it with the same content as the schematic HTML structure we saw in Listing 10.10, as seen in Listing 10.23.
Listing 10.23: Using an initial (incorrect) schematic layout. RED
views/layout.erb
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Learn Enough Ruby Sample App</title> <link rel="stylesheet" type="text/css" href="/stylesheets/main.css"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400" rel="stylesheet"> </head> <body> <a href="/" class="header-logo"> <img src="/images/logo_b.png" alt="Learn Enough logo"> </a> <div class="container"> <div class="content"> <!-- page-specific content --> </div> </div> </body> </html>
As indicated in the caption to Listing 10.23, this layout breaks our test suite:
Listing 10.24: RED
$ bundle exec rake test 3 tests, 6 assertions, 3 failures, 0 errors, 0 skips
The ok? assertions in Listing 10.18 are passing, but the h1 assertions are failing. This is because the site is now a bare layout, as shown in Figure 10.8.
Figure 10.8: The bare layout, with no content.
To get the tests to pass and restore our site to full functionality, all we need to do is replace the HTML comment
with some special Ruby code:
This is our first example of embedded Ruby, which we’ll learn more about in Section 10.4. The special <%= ... %> notation arranges to evaluate the code represented by ... and insert it into the site.
In this case, that code is yield, the keyword used in Section 5.4.1 to yield content to a block, but the truth is that I don’t know offhand exactly how this works or precisely why a block is involved. Indeed, I encourage you to think of <%= yield %> as meaning “special code that inserts the page content into a layout”, and not worry about the details. (If you do much Ruby web development, you’ll soon get used to it—the exact same code is used in Ruby on Rails application layouts.)
Making the replacement suggested above yields (heh) the layout shown in Listing 10.25.
Listing 10.25: Inserting content into the site layout. GREEN
views/layout.erb
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Learn Enough Ruby Sample App</title> <link rel="stylesheet" type="text/css" href="/stylesheets/main.css"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400" rel="stylesheet"> </head> <body> <a href="/" class="header-logo"> <img src="/images/logo_b.png" alt="Learn Enough logo"> </a> <div class="container"> <div class="content"> <%= yield %> </div> </div> </body> </html>
With that, our layout is working, the horrible repeated code has been eliminated, and our tests are GREEN:
Listing 10.26: GREEN
$ bundle exec rake test 3 tests, 6 assertions, 0 failures, 0 errors, 0 skips
A quick check in the browser confirms that things are working as expected (Figure 10.9).
Figure 10.9: Our Home page, now created using a layout.
By the way, it’s worth noting that we could have used a layout file called, say, views/page.erb, in which case we would have had to update app.rb with an explicit hash option telling each page to use that file for the layout: