Home > Articles

This chapter is from the book

10.5 Palindrome Detector

In this section, we’ll complete the sample Sinatra app by adding a working palindrome detector. This will involve putting the Ruby gem developed in Chapter 8 to good use. We’ll also see the first truly working HTML form in the Learn Enough introductory sequence.

Our first step is to add a palindrome gem. I recommend using your own, but if for any reason you didn’t publish one you can use mine, which is shown in Listing 10.43.

Listing 10.43: Adding a palindrome gem.
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'
gem 'mhartl_palindrome', '0.1.0'

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

Then we install as usual:

We also need to include the palindrome gem in our app (Listing 10.44).

Listing 10.44: Adding the palindrome gem to the app.
app.rb

require 'sinatra'
require 'mhartl_palindrome'

get '/' do
  @title = 'Home'
  erb :index
end

get '/about' do
  @title = 'About'
  erb :about
end

get '/palindrome' do
  @title = 'Palindrome Detector'
  erb :palindrome
end

With that prep work done, we’re now ready to add a form to our Palindrome Detector page, which is currently just a placeholder (Figure 10.13). The form consists of three principal parts: a form tag to define the form, a textarea for entering a phrase, and a button for submitting the phrase to the server.

Figure 10.13

Figure 10.13: The current state of the palindrome page.

Let’s work inside out. The button has two attributes: a CSS class for styling and a type indicating that it’s designed to submit information:

The textarea has three attributes: a name attribute, which as we’ll see in a moment passes important information back to the server, along with rows and cols to define the size of the textarea box:

The textarea tag’s content is the default text displayed in the browser, which in this case is just blank.

Finally, the form tag itself has three attributes: a CSS id, which isn’t used here but is conventional to include; an action, which specifies the action to take when submitting the form; and a method indicating the HTTP request method to use:

We saw as early as Listing 1.8 how Sinatra apps define responses to URLs:

Here get is a Sinatra function specifying how to respond when someone hits the root URL / with a GET request, which is the kind of request a web browser sends for an ordinary click. In contrast, a POST request is the kind of request typically submitted by a form. (As you might guess, there’s a corresponding Sinatra function called post for handling this kind of request, as we’ll see in a moment.)

Putting the above discussion together (and adding a br tag to add a line break) yields the form shown in Listing 10.45. Our updated Palindrome Detector page appears in Figure 10.14.

Figure 10.14

Figure 10.14: The new palindrome form.

Listing 10.45: Adding a form to the palindrome page.
views/palindrome.erb

<h1>Palindrome Detector</h1>

<form id="palindrome_tester" action="/check" method="post">
  <textarea name="phrase" rows="10" cols="60"></textarea>
  <br>
  <button class="form-submit" type="submit">Is it a palindrome?</button>
</form>

The form in Listing 10.45 is, apart from cosmetic details, identical to the analogous form developed in Learn Enough JavaScript to Be Dangerous:

In that case, though, we “cheated” by using a JavaScript event listener to intercept the submit request from the form, and no information ever got sent from the client (browser) to the server. (It’s important to understand that, when developing web applications on a local computer, the client and server are the same physical machine, but in general they are different.)

This time, we won’t cheat: The request will really go all the way to the server, which means we’ll have to handle the POST request on the back-end. As hinted above, the way to do this is with the post function:

Here the name of the URL path, /check, matches the value of the action parameter in the form (Listing 10.45).

To get our first hint of what form submission does, we’ll use one of my favorite heavy-handed debugging tricks (Box 5.1), which is to raise an exception right in app.rb. In this case, we’ll raise the contents of a special object called params, called using inspect to ensure that the result is a proper string. The code appears in Listing 10.46, while the result of submitting “Madam, I’m Adam.” in the form appears in Figure 10.15.

Figure 10.15

Figure 10.15: The result of a raise after form submission.

Listing 10.46: Investigating the effects of a form submission.
app.rb

require 'sinatra'
require 'mhartl_palindrome'

get '/' do
  @title = 'Home'
  erb :index
end

get '/about' do
  @title = 'About'
  erb :about
end

get '/palindrome' do
  @title = 'Palindrome Detector'
  erb :palindrome
end

post '/check' do
  raise params.inspect
end

As seen in Figure 10.15, params is a hash (Section 4.4), with key "phrase" and value "Madam, I'm Adam.":

This params hash is created automatically by Sinatra according to the key–value pairs in the form (Listing 10.45). In this case, we have only one such pair, with key given by the name attribute of the textarea ("phrase") and value given by the string entered by the user. By the way, inside the application code it’s possible to use a symbol key instead, and indeed this is the more common convention, so that

extracts the value of the phrase.

Now that we know about the existence and contents of params, detecting a palindrome is easy: Just extract the phrase and call palindrome? on it. If we put the phrase into an instance variable called @phrase, our code would look something like this in plain Ruby:

Listing 10.47: What our palindrome results might look like in plain Ruby.

if @phrase.palindrome?
  puts "\"#{@phrase}\" is a palindrome!"
else
  puts "\"#{@phrase}\ "isn't a palindrome."
end

We can do the same basic thing using embedded Ruby (Section 10.4), only using <%= ... %> instead of interpolation, and surrounding any other code in <% ... %> tags. This is the same syntax we’ve seen before, only without an equals sign =, which tells ERB to evaluate the code but not to insert it into the page. Schematically, it looks something like Listing 10.48.

Listing 10.48: Schematic code for the palindrome result.

<% if @phrase.palindrome? %>
   "<%= @phrase %>" is a palindrome!
<% else %>
    "<%= @phrase %>" isn't a palindrome!
<% end %>

We’ll create a file called result.erb:

The code itself is an expanded version of Listing 10.48 with a few more HTML tags for a better appearance, as shown in Listing 10.49.

Listing 10.49: Displaying the palindrome result using ERB.
views/result.erb

<h1>Palindrome Result</h1>

<% if @phrase.palindrome? %>
  <div class="result result-success">
    <p>"<%= @phrase %>" is a palindrome!</p>
  </div>

<% else %>
  <div class="result result-fail">
    <p>"<%= @phrase %>" isn't a palindrome!</p>
  </div>
<% end %>

All that’s left now is handling the submission, putting the value of params[:phrase] in @phrase, and rendering the result. Since the form issues an HTTP POST request, the trick is to use the post function in place of the get function we’ve used on every page so far. The URL itself is '/check', as indicated by the value of the action attribute in Listing 10.45. The result appears in Listing 10.50.

Listing 10.50: Handling a palindrome form submission.
app.rb

require 'sinatra'
require 'mhartl_palindrome'

get '/' do
  @title = 'Home'
  erb :index
end

get '/about' do
  @title = 'About'
  erb :about
end

get '/palindrome' do
  @title = 'Palindrome Detector'
  erb :palindrome
end

post '/check' do
  @phrase = params[:phrase]
  erb :result
end

With that, our palindrome detector should be working! Let’s see if it can correctly identify one of the most ancient palindromes, the so-called Sator Square first found in the ruins of Pompeii (Figure 10.16).4 (Authorities differ on the exact meaning of the Latin words in the square, but the likeliest translation is “The sower [farmer] Arepo holds the wheels with effort.”)

Figure 10.16

Figure 10.16: A Latin palindrome from the lost city of Pompeii.

Entering the text “SATOR AREPO TENET OPERA ROTAS” (Figure 10.17) and submitting it leads to the result shown in Figure 10.18.

Figure 10.17

Figure 10.17: A Latin palindrome?

Figure 10.18

Figure 10.18: A Latin palindrome!

10.5.1 Form Tests

Our application is now working, but note that testing a second palindrome requires clicking on “IS IT A PALINDROME?” It would be more convenient if we included the same submission form on the result page as well.

To do this, we’ll first add a simple test for the presence of a form tag on the palindrome page. Because the tests we’ll be adding are specific to that page, we’ll create a new test file to contain them:

The test itself is closely analogous to the h1 test in Listing 10.18, as shown in Listing 10.51.

Listing 10.51: Testing for the presence of a form tag. GREEN
palindrome_test.rb

require_relative 'test_helper'

class PalindromeAppTest < Minitest::Test
  include Rack::Test::Methods

  def app
    Sinatra::Application
  end

  def test_form_presence
    get '/palindrome'
    assert doc(last_response).at_css('form')
  end
end

Now we’ll add tests for the existing form submission for both non-palindromes and palindromes. Just as get in tests issues a GET request, post in tests issues a POST request. The first argument of post is the URL, and the second is the params hash:

(Note that this uses the more compact key: value hash notation mentioned in Section 4.4; per the note near the end of Section 10.3, we have also omitted the curly braces.)

To test the response, we’ll verify that the text in the page’s paragraph tag includes the right result. The most elegant way to do this is with assert_-includes from the minitest assertions, where

is effectively equivalent to

using the String#include? method discussed in Section 2.5. (As with assert_equal, using the native assertion is generally more convenient because the failing messages are more descriptive.) For a non-palindrome, the assertion would look something like this:

Taking the ideas above and applying them to both non-palindromes and palindromes gives the tests shown in Listing 10.52 (with only inner lines highlighted for brevity).

Listing 10.52: Adding tests for form submission. GREEN
palindrome_test.rb

require_relative 'test_helper'

class PalindromeAppTest < Minitest::Test
  include Rack::Test::Methods

  def app
    Sinatra::Application
  end

  def test_form_presence
    get '/palindrome'
    assert doc(last_response).at_css('form')
end

  def test_non_palindrome_submission
    post '/check', phrase: "Not a palindrome"
    assert_includes doc(last_response).at_css('p').content, "isn't a palindrome"
  end

  def test_palindrome_submission
    post '/check', phrase: "Able was I, ere I saw Elba."
    assert_includes doc(last_response).at_css('p').content, "is a palindrome"
  end
end

Because we were testing existing functionality, our tests should already be GREEN:

Listing 10.53: GREEN

$ bundle exec rake test
6 tests, 15 assertions, 0 failures, 0 errors, 0 skips

As a capstone to our development, we’ll now add a form on the result page using the RED, GREEN, refactor cycle that is a hallmark of TDD. Without loss of generality, we’ll work in the non-palindrome test; all we need to do is add a form test identical to the one in Listing 10.51, as shown in Listing 10.54.

Listing 10.54: Adding a test for a form on the result page. RED
palindrome_test.rb

require_relative 'test_helper'

class PalindromeAppTest < Minitest::Test
  include Rack::Test::Methods

  def app
    Sinatra::Application
  end

  def test_form_presence
    get '/palindrome'
    assert doc(last_response).at_css('form')
  end

  def test_non_palindrome_submission
    post '/check', phrase: "Not a palindrome"
    assert_includes doc(last_response).at_css('p').content, "isn't a palindrome"
    assert doc(last_response).at_css('form')
  end

  def test_palindrome_submission
    post '/check', phrase: "Able was I, ere I saw Elba."
    assert_includes doc(last_response).at_css('p').content, "is a palindrome"
  end
end

As required, the test suite is now RED:

Listing 10.55: RED

$ bundle exec rake test
6 tests, 16 assertions, 1 failures, 0 errors, 0 skips

We can get the tests to GREEN again by copying the form from palindrome.erb and pasting it into result.erb, as shown in Listing 10.56.

Listing 10.56: Adding a form to the result page. GREEN
views/result.erb

<h1>Palindrome Result</h1>

<% if @phrase.palindrome? %>
  <div class="result result-success">
    <p>"<%= @phrase %>" is a palindrome!</p>
  </div>
<% else %>
  <div class="result result-fail">
    <p>"<%= @phrase %>" isn't a palindrome!</p>
  </div>
<% end %>

<h2>Try another one!</h2>

<form id="palindrome_tester" action="/check" method="post">
  <textarea name="phrase" rows="10" cols="60"></textarea>
  <br>
  <button class="form-submit" type="submit">Is it a palindrome?</button>
</form>

This gets our tests to GREEN:

Listing 10.57: GREEN

$ bundle exec rake test
6 tests, 16 assertions, 0 failures, 0 errors, 0 skips

That cut-and-paste should have set your programmer Spidey-sense tingling though: It’s repetition! Pasting in content is a clear violation of the Don’t Repeat Yourself (DRY) principle. Happily, we saw how to eliminate such duplication in the case of the site navigation by refactoring the code to use a partial (Listing 10.40), which we can apply to this case as well. As with the nav, we’ll first create a separate file for the form HTML:

Then we can fill it with the form (Listing 10.58), while replacing the form with an ERB rendering on the result page (Listing 10.59) and on the main palindrome page itself (Listing 10.60).

Listing 10.58: A partial for the palindrome form. GREEN
views/palindrome_form.erb

<form id="palindrome_tester" action="/check" method="post">
  <textarea name="phrase" rows="10" cols="60"></textarea>
  <br>
  <button class="form-submit" type="submit">Is it a palindrome?</button>
</form>

Listing 10.59: Rendering the form partial on the result page. GREEN
views/result.erb

<h1>Palindrome Result</h1>

<% if @phrase.palindrome? %>
  <div class="result result-success">
    <p>"<%= @phrase %>" is a palindrome!</p>
  </div>
<% else %>
  <div class="result result-fail">
    <p>"<%= @phrase %>" isn't a palindrome!</p>
  </div>
<% end %>

<h2>Try another one!</h2>

<%= erb :palindrome_form %>

Listing 10.60: Rendering the form partial on the main palindrome page. GREEN
views/palindrome.erb

<h1>Palindrome Detector</h1>

<%= erb :palindrome_form %>

As required for a refactoring, the tests are still GREEN!

Listing 10.61: GREEN

$ bundle exec rake test
6 tests, 16 assertions, 0 failures, 0 errors, 0 skips

Submitting the Sator Square palindrome shows that the form on the result page is rendering properly, as shown in Figure 10.19.

Figure 10.19

Figure 10.19: The form on the result page.

Filling the textarea with one of my favorite looooong palindromes (Figure 10.20) gives the result shown in Figure 10.21.5

Figure 10.20

Figure 10.20: Entering a long string in the form’s textarea field.

Figure 10.21

Figure 10.21: That long string is a palindrome!

And with that—“A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal—Panama!”—we’re done with our palindrome detector web application. Whew!

The only thing left is to commit and deploy:

Note that, after pushing once, we can omit the branch name (main) and just type git push heroku. The result is a palindrome application working in production (Figure 10.22)! (To learn how to host a Heroku site using a custom domain instead of a herokuapp.com subdomain, see the free tutorial Learn Enough Custom Domains to Be Dangerous.)

Figure 10.22

Figure 10.22: Our palindrome detector working on the live Web.

10.5.2 Exercises

  1. Confirm by submitting an empty textarea that the palindrome detector currently returns true for the empty string, which is a flaw in the palindrome gem itself. What happens if you submit a bunch of spaces?

  2. In the palindrome gem, write a test asserting that a string of spaces isn’t a palindrome (RED). Then write the application code necessary to get that test to GREEN. Bump the version number and publish your gem as in Section 8.5.1. (You can refer to my version if you’d like some help.)

  3. After waiting a few minutes for RubyGems to update, bump the version number in the Gemfile (Listing 10.43), update the gems using bundle update, and confirm that an empty submission is no longer a palindrome, both locally and (after redeploying) in production.

  4. Make a commit and deploy the changes.

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