Chapters 14 & 15 - Web Apps

Exercise 1: Sinatra routes

The roll_die method below simulates rolling a die with the given number of sides. If you call roll_die(6), you’ll get a random number between 1 and 6. If you call roll_die(20), you’ll get a random number between 1 and 20.

Create three Sinatra routes that use this method:

  • The /roll/4 path should output “Rolling 4 sided die:”, followed by the result of calling roll_die(4).
  • The /roll/6 path should output “Rolling 6 sided die:”, followed by the result of calling roll_die(6).
  • The /roll/20 path should output “Rolling 20 sided die:”, followed by the result of calling roll_die(20).
require 'sinatra'

def roll_die(sides)
  rand(sides) + 1
end

# YOUR CODE HERE

Once you have your server running, you should be able to load any of the paths you’ve set up, and then refresh the browser repeatedly to get different random numbers.

When you’re ready, have a look at our solution.

Exercise 2: ERB templates

Below is a Sinatra app meant to show items in an HTML “unordered list” (the <ul> element). There are two routes.

require 'sinatra'

get('/fruits') do
  @items = ["apples", "oranges", "pears"]
  erb :list
end

get('/meats') do
  @items = ["chicken", "beef", "lamb"]
  erb :list
end

The /meats route should render HTML like this, showing a list of meats:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <ul>
        <li>chicken</li>
        <li>beef</li>
        <li>lamb</li>
    </ul>
  </body>
</html>

…And the /fruits route should render nearly-identical HTML, but with a list of fruits.

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <ul>
        <li>apples</li>
        <li>oranges</li>
        <li>pears</li>
    </ul>
  </body>
</html>

Both routes store arrays in the @items instance variable. And both routes rely on the below ERB code, which is stored in the list.erb file within the views subfolder, to render the list. Your job is to finish the template so that the HTML output matches the samples above.

You’ll need to use a regular embedding tag with the each method to process each item in the list, and an output embedding tag to output the current list item.

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <ul>
      <% # YOUR CODE HERE %>
    </ul>
  </body>
</html>

When you’re ready, have a look at our solution.

Exercise 3: Named parameters

Take your solution to Exercise 1, and convert the /roll/4, /roll/6, and /roll/20 routes to a single route that uses a named parameter for the number of sides. (You’ll need to convert the parameter from a string to an integer before passing it to the roll_die method.)

When you’re ready, have a look at our solution.