- 10.1 Setup
- 10.2 Site Pages
- 10.3 Layouts
- 10.4 Embedded Ruby
- 10.5 Palindrome Detector
- 10.6 Conclusion
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: 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: 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: 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: 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: A Latin palindrome?
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: 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: Entering a long string in the form’s textarea field.
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: Our palindrome detector working on the live Web.
10.5.2 Exercises
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?
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.)
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.
Make a commit and deploy the changes.