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 callingroll_die(4)
. - The
/roll/6
path should output “Rolling 6 sided die:”, followed by the result of callingroll_die(6)
. - The
/roll/20
path should output “Rolling 20 sided die:”, followed by the result of callingroll_die(20)
.
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.
The /meats
route should render HTML like this, showing a list of meats:
…And the /fruits
route should render nearly-identical HTML, but with a list of fruits.
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.
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.