1. Technology
Send to a Friend via Email
You can opt-out at any time. Please refer to our privacy policy for contact information.

Creating Database-driven Apps with Sinatra


Finally, it's all coming together. Having read the previous articles in this series, you're now able to do the following.

This article is the combination of all of the above. It will create a rolodex application that can be used to keep track of contact information. The total line count is about 130 lines, split about half and half with code and views. If you're the type of person who skips right to the code, the code is on the second page.

The Model

The model comes first. It's a simple model with 3 major fields: firstname, lastname and email. More could be added easily if you wish. This application attempts to be DRY (Don't Repeat Yourself) to allow easy modifications.

Having read the previous article on DataMapper, this portion of the code should be nothing new. Note that no key is explicitly defined. Instead, the key is the id column, as the Serial column type implies that it is a key.

The Controller

The controller implements a REST-like interface to the Contacts database. Each of the actions is very short and easy to understand. For example, the /contacts/ action, which displays a list of the contacts, simply renders a Haml view with all of the contacts.

Each action attempts to be as simple as possible. The most complex actions involve retrieving a contact from the database, updating its attribute and either rendering a page or redirecting to another page. And even at that, those actions are only three to four lines long.

As said before, the DRY principle was used here. Besides the layout, there are only three views to be shared between seven controller actions. To do this, a single form view is used in place of both a new and edit view, as well as the use of redirection rather than rendering views. To make any changes, there are only 3 views to update, so changes should be simple.

The Views

The views are simple, barebones Haml. The views list and show are straightforward, showing or listing the contacts. The view form is used twice, and has an extra bit of logic to show the delete button only if the id attribute is set. In order to use this view correctly, you must pass a valid Contact object to the view. To use the view with an empty set of fields (as with the new action), pass an empty Contact object by calling Contact.new.

The Code

That's about it. This code is remarkably simple and should be easy to read. You can find the complete application on the next page. If you want to run it, you'll need Sinatra, Haml, DataMapper, SQLite3 and DataMapper's SQLite3 driver installed. Simply run the Ruby script, wait for Sinatra to start up (this can take a moment as it has to require some large libraries and open the database) and point your web browser to http://localhost:4567/contacts.

  1. About.com
  2. Technology
  3. Ruby