Getting Started with Sinatra

Sing me a song mister Sinatra. In this tutorial I get you started with sinatra, plus improve the folder structure of your app, and serve it up with unicorn.


The Basics

Type sudo mate hello.rb and in the hello.rb put the following:

Now you just need to run the app. Shotgun is great for this. It's a lot like script/server for unicorn apps. (We'll use unicorn to do this later, but for now we'll keep it easy with shotgun)


I like haml so let's bring it into the app now. We've already installed the haml gem so just change your hello.rb file to the following:

Move to folder structure

I like an organized application that can handle future complexity. Let's setup a folder structure to make room for that possibility.

To begin, create a folder with the name of your app. I'm going to call my app careengine. Then, create the directory structure we'll be using.

In app.rb put the following:

This tells our / route to use index.haml from our views. Let's create that file now by type sudo mate views/index.haml.


Now that the app is contained inside a folder structure (slightly similar to rails), let's set the app up to serve itself with unicorn instead of shotgun. (Unicorn is what we will be using on our production server, and It's nice to keep development and production as similar as possible.)

Don't forget to install unicorn: sudo gem install unicorn

Unicorn works with a file so let's create that.

Type sudo mate

Now just run the command 'unicorn' in terminal and then browse to http://localhost:8080 to view your app. Alternatively you can type unicorn -p 3000 to specify the port as 3000.

Great work, you setup a basic sinatra app, improved on the structure, and served it up with unicorn. You are well on your way to building more complex sinatra applications.

You should follow me on twitter here.