By the end of this course, participants should be comfortable programming at a basic level using Ruby. We will learn together using Learn to Program by Chris Pine as a resource. The pace will be determined by course participants.

Exercise 4

Ruby web apps with Sinatra

Sinatra is a DSL (domain specific language) for creating web applications. This sounds complicated, but what it boils down to is that Sinatra has methods that read almost like English that make it easy to create a web app.

Installation

Installing Sinatra is easy. At the command line, run:

gem install sinatra

Sample Web Application

For instance, create a Ruby script named webapp.rb with the following contents

Take note of the "port=XXXX" portion. In this case, since it reads 4567, the web application is available at http://localhost:4567/ Using a browser, navigate to that URL. You should see "Hello World!"

Further Reading

A full introduction to Sinatra is available at the Sinatra website. I encourage you to read over that document, even if some of it does not make sense because it assumes some knowledge of web development. Do focus on the parts you can understand at this point. The exercise below will only require a basic knowledge.

Exercise

Create a simple web application that manages a TODO list. The web application should respond to the following routes:

Since this may be a bit overwhelming, I've given you a skeleton program below and some hints. Copy this program into your git repository, finish it up, and commit it.

require 'sinatra'
# Remember arrays? We'll store the TODO list in an array
items = []
get '/' do
# To iterate through an array, use the #each method (look back at LtP Chapter 7)
# Note that "puts" in Sinatra will only output to the console, not the web
# browser. Instead, build up a string called "response" and return it to
# Sinatra so that will be the response
response = ""
items.each do |item|
# TODO: Build up the response string by concatenating "item" and a line
# break "<br/>" to the string
end
# Keep the line here so that response is returned to sinatra
response
end
get '/add/:item' do
# The new item will be available as params[:item]
# TODO: Insert code to add params[:item] to the global items array here
redirect to('/')
end
get '/remove/:item' do
# The item to be removed will be available as params[:item]
# TODO: Insert code to remove params[:item] from the global items array
# here. You may want to use a method called Array#delete (look it up in the
# documentation!)
redirect to('/')
end