# Singing With Sinatra: The Recall App

This post is part of a series called Singing with Sinatra.
Singing with Sinatra
Singing with Sinatra - The Encore

Welcome to Track 2 of Singing with Sinatra. In part one, we reviewed Routes, how to work with URI parameters, working with forms, and how Sinatra differentiates routes by the HTTP method they were requested by. Today, we're going to extend our knowledge of Sinatra by building a small database-driven app, "Recall," for taking notes/making a to-do list.

We're going to be using a SQLite database to store the notes, and we'll use the DataMapper RubyGem to communicate with the database. Run the following inside a shell to install the relevant Gems:

 1 gem install sqlite3 datamapper dm-sqlite-adapter 

Depending on how you have RubyGems set up on your system, you may need to prefix gem install with sudo.

## The Warm-Up

Let's jump right in by creating a new directory for the project, and creating the application file, recall.rb. Start it off by requiring the relevant gems:

 1 require 'rubygems'  2 require 'sinatra'  3 require 'datamapper' 

Note: If you're running Ruby 1.9 (which you should be), you can drop the "require 'rubygems'" line as Ruby automatically loads RubyGems anyway.

And set up the database with the following:

 1 DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/recall.db")  2 3 class Note  4  include DataMapper::Resource  5  property :id, Serial  6  property :content, Text, :required => true  7  property :complete, Boolean, :required => true, :default => false  8  property :created_at, DateTime  9  property :updated_at, DateTime  10 end  11 12 DataMapper.finalize.auto_upgrade! 

On the first line we're setting up a new SQLite3 database in the current directory, named recall.db. Below that, we're actually setting up a 'Notes' table in the database.

While we're calling the class 'Note', DataMapper will create the table as 'Notes'. This is in keeping with a convention which Ruby on Rails and other frameworks and ORM modules follow.

Inside the class, we're setting up the database schema. The 'Notes' table will have 5 fields. An id field which will be an integer primary key and auto-incrementing (this is what 'Serial' means). A content field containing text, a boolean complete field and two datetime fields, created_at and updated_at.

The very last line instructs DataMapper to automatically update the database to contain the tables and fields we have set, and to do so again if we make any changes to the schema.

At the top is a form to add a new note, and below it is all the notes in the database. To get started, add the following to the application file, recall.rb:

 1 get '/' do  2  @notes = Note.all :.order => :id.desc  3  @title = 'All Notes'  4  erb :home  5 end 

Important Note: Remove the dot ('.') in :.order. (WordPress is interfering with the code sample.)

On the second line you see how we retrieve all the notes from the database. If you've used ActiveRecord (the ORM used in Rails) before, DataMapper's syntax will feel very familiar. The notes are assigned to the @notes instance variable. It's important to use instance variables (that's variables beginning with an @) so that they'll be accessible from within the view file.

We set the @title instance variable, and load the views/home.erb view file through the ERB parser.

Create the views/home.erb view file and start it off with the following:

 1 
 2 
 3   4   5   6 
 7 8 <% # display notes %> 

We have a simple form which POSTs to the home page ('/'), and below that is some ERB code serving as a placeholder for now.

## Layouts

The HTML standards lot amongst you may have suffered a minor stroke after seeing that our home view file contains no doctype or other HTML tags. Well, there's a reason for that. Create a layout.erb file in your views/ directory containing the following:

 1   2   3   4   5  <%= @title + ' | Recall' %>  6   7   8   9   10 
 11 
 12 

Recall

 13 

'cause you're too busy to remember

 14 
 15 
 16 17 
 18  <%= yield %>  19 
 20 21 
 22 

An app for Nettuts+.

 23 
 24   25  

The two interesting parts here are lines 5 and 18. On line 5 you see the first use of the <%= … %> ERB tags. <%= is different from the ordinary <% as it prints what is inside. So here we're displaying the whatever's in the @title instance variable followed by  | Recall for the page's <title> tag.

On line 18 is <%= yield %>. Sinatra will display this layout.erb file on all Routes. And the actual content for that route will be inserted wherever the yield is. yield is a term which essentially means "stop here, insert whatever's waiting, then continue on".

Start up the server with shotgun recall.rb in the shell, and take a look at the home page in the browser. You should see content from the layout file, and the form from the actual home.erb view.

## CSS

In the layout file we included two CSS files. Sinatra can load static files (eg. your CSS, JS, images etc.) from a folder named public/ in the root directory. So create that directory, and inside it two files: reset.css and style.css. The reset contains the HTML5 Boilerplate CSS reset:

 1 /*  2  HTML5 ✰ Boilerplate  3   4  style.css contains a reset, font normalization and some base styles.  5   6  credit is left where credit is due.  7  much inspiration was taken from these projects:  8  yui.yahooapis.com/2.8.1/build/base/base.css  9  camendesign.com/design/  10  praegnanz.de/weblog/htmlcssjs-kickstart  11 */  12 13 /*  14  html5doctor.com Reset Stylesheet (Eric Meyer's Reset Reloaded + HTML5 baseline)  15  v1.6.1 2010-09-17 | Authors: Eric Meyer & Richard Clark  16  html5doctor.com/html-5-reset-stylesheet/  17 */  18 19 html, body, div, span, object, iframe,  20 h1, h2, h3, h4, h5, h6, p, blockquote, pre,  21 abbr, address, cite, code, del, dfn, em, img, ins, kbd, q, samp,  22 small, strong, sub, sup, var, b, i, dl, dt, dd, ol, ul, li,  23 fieldset, form, label, legend,  24 table, caption, tbody, tfoot, thead, tr, th, td,  25 article, aside, canvas, details, figcaption, figure,  26 footer, header, hgroup, menu, nav, section, summary,  27 time, mark, audio, video {  28  margin:0;  29  padding:0;  30  border:0;  31  font-size:100%;  32  font: inherit;  33  vertical-align:baseline;  34 }  35 36 article, aside, details, figcaption, figure,  37 footer, header, hgroup, menu, nav, section {  38  display:block;  39 }  40 41 blockquote, q { quotes:none; }  42 43 blockquote:before, blockquote:after,  44 q:before, q:after { content:''; content:none; }  45 46 ins { background-color:#ff9; color:#000; text-decoration:none; }  47 48 mark { background-color:#ff9; color:#000; font-style:italic; font-weight:bold; }  49 50 del { text-decoration: line-through; }  51 52 abbr[title], dfn[title] { border-bottom:1px dotted; cursor:help; }  53 54 table { border-collapse:collapse; border-spacing:0; }  55 56 hr { display:block; height:1px; border:0; border-top:1px solid #ccc; margin:1em 0; padding:0; }  57 58 input, select { vertical-align:middle; }  59 60 /* END RESET CSS */  61 62 /* font normalization inspired by from the YUI Library's fonts.css: developer.yahoo.com/yui/ */  63 body { font:13px/1.231 sans-serif; *font-size:small; } /* hack retained to preserve specificity */  64 select, input, textarea, button { font:99% sans-serif; }  65 66 /* normalize monospace sizing  67  * en.wikipedia.org/wiki/MediaWiki_talk:Common.css/Archive_11#Teletype_style_fix_for_Chrome */  68 pre, code, kbd, samp { font-family: monospace, sans-serif; }  69 70 /*  71  * minimal base styles  72  */  73 74 body, select, input, textarea {  75  /* #444 looks better than black: twitter.com/H_FJ/statuses/11800719859 */  76  color: #444;  77  /* set your base font here, to apply evenly */  78  /* font-family: Georgia, serif; */  79 }  80 81 /* headers (h1,h2,etc) have no default font-size or margin. define those yourself. */  82 h1,h2,h3,h4,h5,h6 { font-weight: bold; }  83 84 /* always force a scrollbar in non-IE: */  85 html { overflow-y: scroll; }  86 87 /* accessible focus treatment: people.opera.com/patrickl/experiments/keyboard/test */  88 a:hover, a:active { outline: none; }  89 90 a, a:active, a:visited { color: #607890; }  91 a:hover { color: #036; }  92 93 ul, ol { margin-left: 2em; }  94 ol { list-style-type: decimal; }  95 96 /* remove margins for navigation lists */  97 nav ul, nav li { margin: 0; list-style:none; list-style-image: none; }  98 99 small { font-size: 85%; }  100 strong, th { font-weight: bold; }  101 102 td { vertical-align: top; }  103 104 /* set sub, sup without affecting line-height: gist.github.com/413930 */  105 sub, sup { font-size: 75%; line-height: 0; position: relative; }  106 sup { top: -0.5em; }  107 sub { bottom: -0.25em; }  108 109 pre {  110  /* www.pathf.com/blogs/2008/05/formatting-quoted-code-in-blog-posts-css21-white-space-pre-wrap/ */  111  white-space: pre; white-space: pre-wrap; white-space: pre-line; word-wrap: break-word;  112  padding: 15px;  113 }  114 115 textarea { overflow: auto; } /* www.sitepoint.com/blogs/2010/08/20/ie-remove-textarea-scrollbars/ */  116 117 .ie6 legend, .ie7 legend { margin-left: -7px; } /* thnx ivannikolic! */  118 119 /* align checkboxes, radios, text inputs with their label by: Thierry Koblentz tjkdesign.com/ez-css/css/base.css */  120 input[type="radio"] { vertical-align: text-bottom; }  121 input[type="checkbox"] { vertical-align: bottom; }  122 .ie7 input[type="checkbox"] { vertical-align: baseline; }  123 .ie6 input { vertical-align: text-bottom; }  124 125 /* hand cursor on clickable input elements */  126 label, input[type="button"], input[type="submit"], input[type="image"], button { cursor: pointer; }  127 128 /* webkit browsers add a 2px margin outside the chrome of form elements */  129 button, input, select, textarea { margin: 0; }  130 131 /* colors for form validity */  132 input:valid, textarea:valid { }  133 input:invalid, textarea:invalid {  134  border-radius: 1px; -moz-box-shadow: 0px 0px 5px red; -webkit-box-shadow: 0px 0px 5px red; box-shadow: 0px 0px 5px red;  135 }  136 .no-boxshadow input:invalid, .no-boxshadow textarea:invalid { background-color: #f0dddd; }  137 138 /* These selection declarations have to be separate.  139  No text-shadow: twitter.com/miketaylr/status/12228805301  140  Also: hot pink. */  141 ::-moz-selection{ background: #FF5E99; color:#fff; text-shadow: none; }  142 ::selection { background:#FF5E99; color:#fff; text-shadow: none; }  143 144 /* j.mp/webkit-tap-highlight-color */  145 a:link { -webkit-tap-highlight-color: #FF5E99; }  146 147 /* make buttons play nice in IE:  148  www.viget.com/inspire/styling-the-button-element-in-internet-explorer/ */  149 button { width: auto; overflow: visible; }  150 151 /* bicubic resizing for non-native sized IMG:  152  code.flickr.com/blog/2008/11/12/on-ui-quality-the-little-things-client-side-image-resizing/ */  153 .ie7 img { -ms-interpolation-mode: bicubic; } 

And style.css contains some basic styling to make the app look pretty:

 1 body {  2  margin: 35px auto;  3  width: 640px;  4 }  5 6 header {  7  text-align: center;  8  margin: 0 0 20px;  9 }  10 11 header h1 {  12  display: inline;  13  font-size: 32px;  14 }  15 16 header h1 a:link, header h1 a:visited {  17  color: #444;  18  text-decoration: none;  19 }  20 21 header h2 {  22  font-size: 16px;  23  font-style: italic;  24  color: #999;  25 }  26 27 #main {  28  margin: 0 0 20px;  29 }  30 31 #add {  32  margin: 0 0 20px;  33 }  34 35 #add textarea {  36  height: 30px;  37  width: 510px;  38  padding: 10px;  39  border: 1px solid #ddd;  40 }  41 42 #add input {  43  height: 50px;  44  width: 100px;  45  margin: -50px 0 0;  46  border: 1px solid #ddd;  47  background: white;  48 }  49 50 #edit textarea {  51  height: 30px;  52  width: 480px;  53  padding: 10px;  54  border: 1px solid #ddd;  55 }  56 57 #edit input[type=submit] {  58  height: 50px;  59  width: 100px;  60  margin: -50px 0 0;  61  border: 1px solid #ddd;  62  background: white;  63 }  64 65 #edit input[type=checkbox] {  66  height: 50px;  67  width: 20px;  68 }  69 70 article {  71  border: 1px solid #eee;  72  border-top: none;  73  padding: 15px 10px;  74 }  75 76 article:first-of-type {  77  border: 1px solid #eee;  78 }  79 80 article:nth-child(even) {  81  background: #fafafa;  82 }  83 84 article.complete {  85  background: #fedae3;  86 }  87 88 article span {  89  font-size: 0.8em;  90 }  91 92 p {  93  margin: 0 0 5px;  94 }  95 96 .meta {  97  font-size: 0.8em;  98  font-style: italic;  99  color: #888;  100 }  101 102 .links {  103  font-size: 1.8em;  104  line-height: 0.8em;  105  float: right;  106  margin: -10px 0 0;  107 }  108 109 .links a {  110  display: block;  111  text-decoration: none;  112 } 

Refresh the page in your browser and everything should be more styled. Don't worry about this CSS too much; it just makes things look a bit prettier!

## Adding a Note to the Database

Right now if you try submitting the form on the home page, you're going to get a route error. Let's create the POST route for the home page now:

 1 post '/' do  2  n = Note.new  3  n.content = params[:content]  4  n.created_at = Time.now  5  n.updated_at = Time.now  6  n.save  7  redirect '/'  8 end 

So when a post request is made on the homepage, we create a new Note object in n (thanks to the DataMapper ORM, Note.new represents a new row in the notes table in the database). The content field is set to the submitted data from the textarea and the created_at and updated_at datetime fields are set to the current timestamp.

The new note is then saved, and the user redirected back to the homepage where the new note will be displayed.

## Displaying the Notes

So we've added a new note, but we can't see it on the homepage yet as we haven't wrote the code for it. Inside the views/home.erb view file, replace the <%# display notes %> line with:

 1 <% @notes.each do |note| %>  2 
>  3 

 4  <%= note.content %>  5    6 

 7   10 

Created: <%= note.created_at %>

 11 
 12 <% end %> 

On the first line we begin a loop through each of the @notes (alternatively, we could have wrote for note in @notes, but using a block, as we are here, is a better practice). On line 2, we give the <article> a class of complete if the current note is set to complete. The rest should be pretty straight forward.

## Editing a Note

So we can add and view notes. Now we just need the ability to edit and delete them.

You may have noticed that in our home.erb view we set an  link for each note to what is essentially /:id, so let's create that route now:

 1 get '/:id' do  2  @note = Note.get params[:id]  3  @title = "Edit note ##{params[:id]}"  4  erb :edit  5 end 

We retrieve the requested note from the database using the ID provided, set up a @title variable, and load the views/edit.erb view file through the ERB parser.

Enter the following for the views/edit.erb view:

 1 <% if @note %>  2 
 3   4   5  >  6   7   8 

Delete

 9 <% else %>  10 

 11 <% end %> 

This is a fairly simple view. A form which points back to the current page, a textarea containing the content of the note and a checkbox which gets checked if the note is set to complete.

But look at the third line. Mysterious. To explain this, we need to side-track a little.

### RESTful Services

You've heard of the two terms GET and POST.

• GET: The most common. It's generally for requesting a page, and can be bookmarked.
• POST: Used for submitting data and can not be bookmarked.

But GET and POST aren't the only "HTTP verbs" - there's two more you should know about: PUT and DELETE.

Technically, POST should only be used for creating something - like creating a new Note in your awesome new web app, for example.

PUT is the verb for modifying something. And DELETE, you guessed it, is for deleting something.

Having these four verbs is a great way to separate an app up. It's logical. Unfortunately, web browsers don't actually support PUT or DELETE requests, which is why you've likely never heard of them before.

So, getting back on track here, if we want to logically split our app up (which Sinatra encourages), we have to fake these PUT and DELETE requests. You'll see our form's action is set to post. The hidden _method input field which we've set to put on the third line lets Sinatra fake this PUT request, while actually using a POST. Rails, among other frameworks, do things a similar way.

## Let us PUT

Now we've faked our PUT request, we can create a route for it:

 1 put '/:id' do  2  n = Note.get params[:id]  3  n.content = params[:content]  4  n.complete = params[:complete] ? 1 : 0  5  n.updated_at = Time.now  6  n.save  7  redirect '/'  8 end 

It's all pretty simple. We get the relevant note using the ID in the URI, set the fields to the new values, save, and redirect home. Notice how on the fourth line we're using a ternary operator to set n.complete to 1 if params[:complete] exists, or 0 otherwise. This is because the value of a checkbox is only submitted with a form if it is checked, so we're simply checking for the existence of it.

## Deleting a Note

In our edit.erb view, we added a 'Delete' link to what is essentially the path /:id/delete. Add this to your application file:

 1 get '/:id/delete' do  2  @note = Note.get params[:id]  3  @title = "Confirm deletion of note ##{params[:id]}"  4  erb :delete  5 end 

On this page we'll get confirmation from the user that they actually want to delete this note. Create the view file at views/delete.erb with the following:

 1 <% if @note %>  2 

Are you sure you want to delete the following note: "<%= @note.content %>"?

 3 
 4   5   6  Cancel  7   8 <% else %>  9 

 10 <% end %> 

Note that just like how we faked a PUT request by setting a hidden _method input field, we're now faking a DELETE request.

## The DELETE Route

I'm sure you're getting the hang of this by now. The delete route is:

 1 delete '/:id' do  2  n = Note.get params[:id]  3  n.destroy  4  redirect '/'  5 end 

Try it out! You should now be able to view, add, edit and remove notes. There's just one more thing…

## Marking a Note as "Complete"

Right now if you want to set a note as complete you have to go into the Edit view and check the box on that page. Let's make that process a bit simpler.

Back when we set up the main home page, we included a /:id/complete link on each note. Let's make that route now, which will simply set a note as complete (or incomplete if it was already set to complete):

 1 get '/:id/complete' do  2  n = Note.get params[:id]  3  n.complete = n.complete ? 0 : 1 # flip it  4  n.updated_at = Time.now  5  n.save  6  redirect '/'  7 end 

## Conclusion

You and Sinatra pull off one crackin' duet! You've very quickly written a simple web app which performs all the CRUD operations you'd expect an app to do. It's written in super-sexy-clean Ruby code, and is separated into its logical parts.

In the final part of Singing with Sinatra, the Encore, we'll improve on error handling, secure the app from XSS and create an RSS feed for the notes.

Note: You can browse the final project files for this tutorial over at GitHub.