Home > Articles

This chapter is from the book

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'
Rake::TestTask.new do |t|   t.pattern = 'test/*_test.rb'   t.warning = false end task :default => [:test]

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

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

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:

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020