- 10.1 Setup
- 10.2 Site Pages
- 10.3 Layouts
- 10.4 Embedded Ruby
- 10.5 Palindrome Detector
- 10.6 Conclusion
10.4 Embedded Ruby
Now that we’ve defined a proper layout, in this section we’ll use embedded Ruby (seen ever-so-briefly in Section 10.3) to add a couple of nice refinements to our site:variable titlesandnavigation. Variable titles are HTMLtitletag contents that vary from page to page, giving each page a nice polish of customization. Navigation, meanwhile, saves us the hassle of having to type each sub-page in by hand—certainly not the kind of user experience we’re trying to create.
Our variable titles will combine abase title在每个页面都是一样的,那一块t varies based on the page’s name. In particular, for our Home, About, and Palindrome Detector pages, we want the titles to look something like this:
Our strategy has three steps:
WriteGREENtests for the current page title.
WriteREDtests for the variable titles.
Get toGREENby adding the variable component of the title.
Note that Steps 2 & 3 constitute TDD—writing the tests for the variable title is easier than getting them to pass, which is one of the cases for TDD described in Box 8.1.
To get started with Step 1, we’ll use thedochelper introduced in Listing 10.17 to extract thetextcomponent of thetitletag. Recalling from Listing 10.18 that we can usedoc.at_css(
We can then find the title content using theNokogiricontentmethod:
This lets us add assertions for the title content to the tests in Listing 10.18, using the sameassert_equalmethod we saw in Listing 8.21. The result appears in Listing 10.27.
Listing 10.27:Adding assertions for the base title content.GREEN
test/site_pages_test.rb
require_relative'test_helper'classPalindromeAppTest<Minitest::TestincludeRack::Test::MethodsdefappSinatra::Applicationenddeftest_indexget'/'assert last_response.ok? assert doc(last_response).at_css('h1')title_content=doc(last_response).at_css('title').contentassert_equal"Learn Enough Ruby Sample App", title_contentenddeftest_aboutget'/about'assert last_response.ok? assert doc(last_response).at_css('h1')title_content=doc(last_response).at_css('title').contentassert_equal"Learn Enough Ruby Sample App", title_contentenddeftest_palindromeget'/palindrome'assert last_response.ok? assert doc(last_response).at_css('h1')title_content=doc(last_response).at_css('title').contentassert_equal"Learn Enough Ruby Sample App", title_contentend end
As required, the tests areGREEN:
Listing 10.28:GREEN
$bundleexecraketest3 tests, 9 assertions, 0 failures, 0 errors, 0 skips
Now we’re ready for Step 2—all we need to do is add the vertical bar|and the page-specific titles, as shown in Listing 10.29. Note that we’ve broken the Palindrome Detector assertion into two lines, in accordance with the 80-column rule (Box 2.2). (Improving this by adding an instance variable to eliminate the duplication of the base title is left as an exercise (Section 10.4.1).)
Listing 10.29:Adding assertions for the variable title content.RED
test/site_pages_test.rb
require_relative'test_helper'classPalindromeAppTest<Minitest::TestincludeRack::Test::MethodsdefappSinatra::Applicationenddeftest_indexget'/'assert last_response.ok? assert doc(last_response).at_css('h1') title_content=doc(last_response).at_css('title').contentassert_equal"Learn Enough Ruby Sample App | Home", title_contentenddeftest_aboutget'/about'assert last_response.ok? assert doc(last_response).at_css('h1') title_content=doc(last_response).at_css('title').contentassert_equal"Learn Enough Ruby Sample App | About", title_contentenddeftest_palindromeget'/palindrome'assert last_response.ok? assert doc(last_response).at_css('h1') title_content=doc(last_response).at_css('title').contentassert_equal"Learn Enough Ruby Sample App | Palindrome Detector",title_contentend end
Because we haven’t updated the application code, the tests are nowRED:
Listing 10.30:RED
$bundleexecraketest3 tests, 9 assertions, 3 failures, 0 errors, 0 skips
Now for Step 3. The trick is to use an instance variable (Section 7.1) together with embedded Ruby to add the variable component of the title to the site layout, as shown in Listing 10.31.
Listing 10.31:Adding a variable component to the title.RED
views/layout.erb
<html><head><metacharset="utf-8"><title>Learn Enough Ruby Sample App |<%=@title%>title>. . .
As noted briefly in Section 10.3, the<%= ... %>syntax evaluates the code represented by...and inserts it into the site at that point. In this case, that content is simply@title.
But what is@title, and where does it come from? It turns out that in Sinatra (and also in Rails), instance variables defined in controllers are automatically available in views. This means that we can define an@titlevariable for each of our pages, and it will automatically show up in the title thanks to Listing 10.31. The result appears in Listing 10.32.
Listing 10.32:Adding@titlevariables to each page.GREEN
app.rb
require'sinatra'get'/'do@title='Home'erb:indexendget'/about'do@title='About'erb:aboutendget'/palindrome'do@title='Palindrome Detector'erb:palindromeend
With that, our tests are passing!
Listing 10.33:GREEN
$bundleexecraketest3 tests, 9 assertions, 0 failures, 0 errors, 0 skips
Of course, it’s probably a good idea to double-check in the browser, just to make sure (Figure 10.10).
Figure 10.10: Confirming the correct variable titles in the browser.
Now that we have a proper layout file, adding navigation to every page is easy. The nav code appears in Listing 10.34, with the result shown inFigure 10.11.
Figure 10.11: The site navigation.
Listing 10.34:Adding site navigation.
views/layout.erb
<html><head><metacharset="utf-8"> <title>Learn Enough Ruby Sample App |<%=@title%>title> <linkrel="stylesheet"type="text/css"href="/stylesheets/main.css"> <linkhref="https://fonts.googleapis.com/css?family=Open+Sans:300,400"rel="stylesheet"> head> <body><ahref="/"class="header-logo"><imgsrc="/images/logo_b.png"alt="Learn Enough logo"> a><divclass="container"><headerclass="header"><nav><ulclass="header-nav"><li><ahref="/">Homea>li><li><ahref="/palindrome">Is It a Palindrome?a>li><li><ahref="/about">Abouta>li>ul>nav>header><divclass="content"><%=yield%>div> div> body> html>
As a final flourish, we’ll factor the navigation from Listing 10.34 into a separate file, sometimes called apartial. This will lead to a nicely clean and tidy layout page.
Because this involves refactoring the site, we’ll add a simple test (per Box 8.1) to catch any regressions. Because the navigation appears on the site layout, we could use any page to test for its presence, and for convenience we’ll use the index page. As shown in Listing 10.35, all we need to do is assert the existence of anavtag.
Listing 10.35:Testing the navigation.GREEN
test/site_pages_test.rb
require_relative'test_helper'classPalindromeAppTest<Minitest::TestincludeRack::Test::MethodsdefappSinatra::Applicationenddeftest_indexget'/'assert last_response.ok? assert doc(last_response).at_css('h1') title_content=doc(last_response).at_css('title').content assert_equal"Learn Enough Ruby Sample App | Home", title_contentassert doc(last_response).at_css('nav')end. . .end
Because the nav was already added, the tests should beGREEN:
Listing 10.36:GREEN
$ bundle exec rake test 3 tests, 10 assertions, 0 failures, 0 errors, 0 skips
It’s a good practice to watch the tests change toREDto make sure we’re testing the right thing, so we’ll start by cutting the navigation (Listing 10.37) and pasting it into a separate file, which we’ll callnavigation.erb(Listing 10.38):
Listing 10.37:Cutting the navigation.RED
views/layout.erb
<html><head><metacharset="utf-8"> <title>Learn Enough Ruby Sample App |<%=@title%>title> <linkrel="stylesheet"type="text/css"href="/stylesheets/main.css"> <linkhref="https://fonts.googleapis.com/css?family=Open+Sans:300,400"rel="stylesheet"> head> <body><ahref="/"class="header-logo"><imgsrc="/images/logo_b.png"alt="Learn Enough logo"> a> <divclass="container"><divclass="content"><%=yield%>div> div> body> html>
Listing 10.38:Adding a navigation partial.RED
views/navigation.erb
<headerclass="header"><nav><ulclass="header-nav"><li><ahref="/">Homea>li> <li><ahref="/palindrome">Is It a Palindrome?a>li> <li><ahref="/about">Abouta>li> ul> nav> header>
You should confirm that the tests are nowRED:
Listing 10.39:RED
$bundleexecraketest3 tests, 10 assertions, 1 failures, 0 errors, 0 skips
To restore the navigation, we can use embedded Ruby to evaluate the sameerbfunction we’ve been using inapp.rb:
This code automatically looks for a file inviews/navigation.erb, evaluates the result, and inserts the return value where it was called.
Putting this code into the layout gives Listing 10.40.
Listing 10.40:Evaluating the nav partial in the layout.GREEN
views/layout.erb
<html><head><metacharset="utf-8"> <title>Learn Enough Ruby Sample App |<%=@title%>title> <linkrel="stylesheet"type="text/css"href="/stylesheets/main.css"> <linkhref="https://fonts.googleapis.com/css?family=Open+Sans:300,400"rel="stylesheet"> head> <body><ahref="/"class="header-logo"><imgsrc="/images/logo_b.png"alt="Learn Enough logo"> a> <divclass="container"><%=erb:navigation%><divclass="content"><%=yield%>div> div> body> html>
With the code in Listing 10.40, our test suite is once againGREEN:
Listing 10.41:GREEN
$bundleexecraketest3 tests, 10 assertions, 0 failures, 0 errors, 0 skips
A quick click over to the About page confirms that the navigation is working (Figure 10.12). Sweet!
Figure 10.12: The navigation menu on the About page.
10.4.1 Exercises
We can eliminate some duplication in Listing 10.29 by creating asetupmethod (which is automatically run before each test) that defines an instance variable for the base title, as shown in Listing 10.42. Confirm that this code still gives aGREENtest suite.
Use embedded Ruby to include a call toTime.now(Section 4.2) somewhere on the index page. What happens when you refresh the browser?
Make a commit and deploy the changes. (If you did the previous exercise, undo those changes first.)
Listing 10.42:Adding asetupmethod to eliminate some duplication.GREEN
test/site_pages_test.rb
require_relative'test_helper'classPalindromeAppTest<Minitest::TestincludeRack::Test::MethodsdefappSinatra::Applicationenddefsetup@base_title="Learn Enough Ruby Sample App"enddeftest_indexget'/'assert last_response.ok? assert doc(last_response).at_css('h1') title_content=doc(last_response).at_css('title').contentassert_equal"#{@base_title}| Home", title_contentenddeftest_aboutget'/about'assert last_response.ok? assert doc(last_response).at_css('h1') title_content=doc(last_response).at_css('title').contentassert_equal"#{@base_title}| About", title_contentenddeftest_palindromeget'/palindrome'assert last_response.ok? assert doc(last_response).at_css('h1') title_content=doc(last_response).at_css('title').contentassert_equal"#{@base_title}| Palindrome Detector", title_contentend end