Home>Articles

This chapter is from the book

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:

  1. WriteGREENtests for the current page title.

  2. WriteREDtests for the variable titles.

  3. 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()to select the first tag with a given tag name, we can find thetitletag as follows:

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

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

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

Figure 10.12: The navigation menu on the About page.

10.4.1 Exercises

  1. 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.

  2. Use embedded Ruby to include a call toTime.now(Section 4.2) somewhere on the index page. What happens when you refresh the browser?

  3. 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

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

培生提供feedbac可能提供机会k 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

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


这个网站不是指向ag)以下儿童e 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.

Requests and Contact


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