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 followedLearn Enough CSS & Layout to Be Dangerous, you’ll know that theLayoutin the title referred to page layout generally—using Cascading Style Sheets to move elements around on the page, align them properly, etc.— but we alsosawthat doing this properly requires defininglayout templatesthat 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.

<html><head><metacharset="utf-8"> <title>Learn Enough Ruby Sample Apptitle> <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">div> div> body> html>

Everything except the page-specific content (indicated by the highlighted HTML comment) is the same on each page. InLearn Enough CSS & Layout to Be Dangerous, we eliminated this duplication usingJekyll templates; in this tutorial, we’ll useSinatra layoutsinstead.

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?

它的确。这就是问题m 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 ahugeimprovement over testing web apps by hand.)

To get started, we’ll add some more gems to ourGemfile, this time in agroupcalled:testthat 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:testdogem'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 installingnokogiri(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 usingrequire_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 aRakefile告诉utility how to run the tests:

The contents are shown in Listing 10.13.

Listing 10.13:Configuringto run tests.
Rakefile

require'rake/testtask'
Rake::TestTask.newdo|t|t.pattern='test/*_test.rb't.warning=falseendtask: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 upsomething, as indicated by theHTTP response code200 (OK), which we can do like this:

Here we use thegetcommand in the test to issue aGETrequest to the root URL /, which automatically creates an object calledlast_responseas a side effect. We can then use a minitest assertion (Section 8.2) using the boolean methodok?, 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 theofficial 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'classPalindromeAppTest<Minitest::TestincludeRack::Test::MethodsdefappSinatra::Applicationenddeftest_indexget'/'assert last_response.ok?enddeftest_aboutget'/about'assert last_response.ok?enddeftest_palindromeget'/palindrome'assert last_response.ok?end end

With the setup in Listing 10.13, we can useto execute the test suite as follows:

Listing 10.15:GREEN

$bundleexectest3 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 runby itself:3

Listing 10.16:GREEN

$bundleexec3 tests, 3 assertions, 0 failures, 0 errors, 0 skips

We’ll continue to use耙testfor 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 nottoostringent—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 anh1tag somewhere in the document.

In order to do this, we’ll write a short function intest_helper.rbto return adocobject, akin to thedocumentobjectin 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 abodyattribute representing the HTML body (the full page, not just thebodytag). This means we can definedocas 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.defdoc(response)Nokogiri::HTML(response.body)end

Now we’re ready to usedocto find theh1(if any) on the page. One possibility would be to usedoc.cssas in, e.g., Listing 9.12:

In the present case, though, we only need to see if there’sanyh1tag, 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, calledat_css:

Because this will benilif there’s noh1and non-nilotherwise, 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 anh1tag.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')enddeftest_aboutget'/about'assert last_response.ok?assert doc(last_response).at_css('h1')enddeftest_palindromeget'/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 toget) 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 beGREENas required:

Listing 10.19:GREEN

$bundleexectest3 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 Apph1><p>This is the sample Sinatra app for<ahref="https://www.learnenough.com/ruby-tutorial"><em>Learn Enough Ruby to Be Dangerousem>a>。学习更多关于the <ahref="/about">Abouta> page. p><p>Click the <ahref="https://en.wikipedia.org/wiki/Sator_Square">Sator Squarea> below to run the custom <ahref="/palindrome">Palindrome Detectora>。p><aclass="sator-square"href="/palindrome"><imgsrc="/images/sator_square.jpg"alt="Sator Square"> a>

Listing 10.21:The core About view.
views/about.erb

<h1>Abouth1><p>This site is the final application in <ahref="https://www.learnenough.com/ruby-tutorial"><em>Learn Enough Ruby to Be Dangerousem>a> by <ahref="https://www.michaelhartl.com/">Michael Hartla>, a tutorial introduction to the <ahref="https://www.ruby-lang.org/en/">Ruby programming languagea> that is part of <ahref="https://www.learnenough.com/">LearnEnough.coma>。p><p><em>Learn Enough Ruby to Be Dangerousem> is a natural prerequisite to the <ahref="https://www.railstutorial.org/">>Ruby on Rails Tutorialem>a>, a book and video series that is one of the leading introductions to web development. <em>Learn Enough Rubyem> is also an excellent choice <em>afterem> the <em>Rails Tutorialem> for those who prefer to start with the latter first. p>

Listing 10.22:The core Palindrome Detector view.
views/palindrome.erb

<h1>Palindrome Detectorh1><p>This will be the palindrome detector.p>

Having stripped all the layout material from our pages, we’ll now create a file calledlayout.erbin theviewsdirectory 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

<html><head><metacharset="utf-8"> <title>Learn Enough Ruby Sample Apptitle> <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">div> div> body> html>

As indicated in the caption to Listing 10.23, this layout breaks our test suite:

Listing 10.24:RED

$bundleexectest3 tests, 6 assertions, 3 failures, 0 errors, 0 skips

Theok?assertions in Listing 10.18 are passing, but theh1assertions are failing. This is because the site is now a bare layout, as shown inFigure 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 ofembedded 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 isyield, 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

<html><head><metacharset="utf-8"> <title>Learn Enough Ruby Sample Apptitle> <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>

With that, our layout is working, the horrible repeated code has been eliminated, and our tests areGREEN:

Listing 10.26:GREEN

$bundleexectest3 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 updateapp.rbwith 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

调查和问题,我们收集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, simplyemailinformation@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 ourContact 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

这个网站使用cookie和类似的技术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 theAccount page. If a user no longer desires our service and desires to delete his or her account, please contact us atcustomer-service@informit.comand 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.e-skidka.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 toNevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read ourSupplemental privacy statement for California residentsin conjunction with this Privacy Notice. TheSupplemental privacy statement for California residentsexplains 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.

请求和联系


Pleasecontact usabout 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