You are on page 1of 15

Fr

ee

Sinatra is a Ruby framework that is widely used in the IT


industry. You can use it to make a single-page web app or
a large-scale one. With the increased online footprint, you
can create and deploy your own application.
Whether you are new to online learning or a seasoned
expert, this book will provide you with the skills you need
to successfully create, customize, and deploy a Sinatra
application. Starting from the beginning, this book will
cover how to install Ruby and Sinatra, construct the
backend, design and customize the frontend layout,
and utilize the innovative and user-friendly features
of Object relational mapping (ORM). By sequentially
working through the steps in each chapter, you will
quickly master Sinatra's features and be able to create
your own application.

What you will learn from this book

Extend the code to include CSS in


different ways
Create projects and understand MVC
Design the frontend with Twitter Bootstrap

Implement sessions that can be used across


multiple pages

C o m m u n i t y

Sudeep Agarwal

Who this book is written for

Utilize the innovative and user-friendly features


of ORMs
Manoj Sehrawat

$ 29.99 US
19.99 UK

P U B L I S H I N G

Work with layouts and template routes

Use the MySQL/SQLite gem to communicate


with databases

community experience distilled

pl

Install and set up Ruby and Sinatra

With ample screenshots and code that offers a play-by-play


account of how to build an application, Learning Sinatra
will ensure your success with this cutting-edge framework.

Learning Sinatra is a great place to start your first


Sinatra application. It doesn't matter whether you have
written a web application before or not, though some
basic knowledge of programming is essential.

Learning Sinatra

Learning Sinatra

Sa
m

D i s t i l l e d

Learning Sinatra
Design and deploy your own web application in minutes
using Sinatra

Prices do not include


local sales tax or VAT
where applicable

Visit www.PacktPub.com for books, eBooks,


code, downloads, and PacktLib.

E x p e r i e n c e

Sudeep Agarwal
Manoj Sehrawat

In this package, you will find:

The authors biography


A preview chapter from the book, Chapter 1 'Introduction to Sinatra'
A synopsis of the books content
More information on Learning Sinatra

About the Authors


Sudeep Agarwal is a site reliability engineer at Inmobi with a total of four years

of experience in the industry. He was with Directi for 3 years right after finishing his
education from NIT Trichy. At Directi, he was a part of the team that wrote one of
the most widely used in-house web-based applications; this is where his interest in
Sinatra started and he used it to write some of his personal projects. Although he is
not writing a lot of web applications at Inmobi, he is still contributing to one of the
ORMsRuby Object Mapper.

Manoj Sehrawat is an enthusiastic software developer who loves coding and

learning new things. He has around 5 years of experience in software development.


Manoj holds an MCA from KIIT, Gurgaon and a BCA from IGNOU. Currently, he is
the associate technical lead at TravelTriangle. TravelTriangle is India's first full stack
holiday marketplace that connects travelers with verified travel agents. Before joining
TravelTriangle, Manoj was working with StudyPad and Fizzy Software Pvt Ltd as
a senior software developer. His primary focus is the design and construction of
scalable and optimized web applications and APIs using a Ruby-based development
stack with frameworks such as Ruby on Rails, Sinatra, and others. He is passionate
about refactoring, optimizing code, and building scalable solutions with simplicity.

Preface
This book will help you understand the basic concepts of Sinatra and build
lightweight web applications. The book follows a step-by-step course, right from
setting up Ruby and installing Sinatra to inculcating best practices for writing
beautiful code. By the end, you will have a running Sinatra app ready and the
confidence to write more apps by yourself.

What this book covers


Chapter 1, Introduction to Sinatra, helps you set up Sinatra and see a sample Hello
World app, followed by a quick comparison with Rails.
Chapter 2, Introduction to Ruby, is intended for Ruby newbies, which helps in setting
up Ruby using rvm and understanding how to write code in Ruby.
Chapter 3, Hello World, helps you write the skeleton of a ToDo app and understand it
line by line.
Chapter 4, Modeling the Backend, introduces the concept of ORMs to the user, which is
required in order to write the ToDo app.
Chapter 5, Handling HTTP Requests, introduces the concept of controllers and explains
how the request-response transaction is implemented.
Chapter 6, Designing the Frontend Layout, introduces HAML and Twitter Bootstrap,
which is used to make beautiful user interfaces easily.

Preface

Chapter 7, Handling User Data, shows you how to create a form and its necessary
attributes, and explains how it works. We will see the importance and usage of the
method and action attributes of a form. We will create a for loop to add a List
and Items of a list to a single form, where we will see how we can add an array of
values to the HTML input. You will also learn how to add items to the form through
JavaScript dynamically using a simple dummy template. We will see how to handle
data at the backend sent by a user through filling in a form, and discuss validations
and the types of validation.
Chapter 8, Connecting to a Database, covers how to connect to a database (MySQL) with
various necessary parameters. You will learn how to use the mysql gem with sequel.
We will also cover how to open and use an interactive console with Sinatra and Sequel
and the details of Sequel models with various useful class-level and instance-level
methods. We will discuss hooks and callbacks available and associations with eager
loading and joins in order to scale and optimize the application.
Chapter 9, Authentication and Authorization, shows you the basics of a session in
general and how we can configure it with Sinatra, both with simple and advanced
options. We will see the various useful methods of a session object and the meaning
of authentication and authorization individually.
Chapter 10, Deploying the App, discusses what deployment is, Heroku, and
how we can use Heroku to deploy our app. You will also learn the initial setup
steps that we need to do on Heroku, and about various Heroku commands and
their billing models.

Introduction to Sinatra
Sinatra is a Ruby-based application framework used to create web applications
quickly. It can be used to write simple single-page applications or large and complex
ones. Sinatra is very lightweight as it does not include a variety of gems, though the
user can include gems as required.
Sinatra is widely used across the globe and has gained a lot of popularity because
of its flexibility. It does not follow the Model-View-Controller (MVC) architectural
pattern completely but it is fairly simple to build one on top of Sinatra. Sinatra is a
View-Controller framework.
If you have been working with Ruby, you can go ahead and try out the codes;
otherwise, you can go ahead with this chapter as we will be covering some basic
Ruby in the next chapter. In this chapter, we will be discussing the following topics:

Model-View-Controller

How Sinatra is an MVC framework

When to use Sinatra and when not to use it

Other popular MVC frameworks

What is MVC?
The MVC (Model-View-Controller) is an architectural pattern that divides the
application in three parts, namely, the model (the data), view (the user interfaces),
and controller (the interconnections between the model and view).

[1]

Introduction to Sinatra

MVC separates the code based on their responsibilities and makes it easier to
understand and maintain:

Figure 1-1: MVC components

The concept of MVC will be clearer once we get into the examples using Sinatra.

Installing Sinatra
Sinatra is just another gem and there is no special way to install it. We use the gem

install command:

$ gem install sinatra

This will install the latest version of the Sinatra gem and all its dependencies on your
system. To see which version is installed, use the following:
$ gem list sinatra

[2]

Chapter 1

Writing your first Sinatra application


Let's see how to write a bare minimum Sinatra application. We will open a new file
and write the following code:
1 require 'sinatra'
2 get '/' do
3
return 'Hello World!'
4 end

Save the file with a .rb extension (say, helloworld.rb) and execute this on the
command line:
$ ruby helloworld.rb

This will interpret the code and start the built-in server.
Now, we open the browser and point it to http://localhost:4567.
What did the code do?
1.require 'sinatra'

This tells the Ruby interpreter to load the Sinatra gem:


3 get '/' do
4
return 'Hello World!'
5 end

This forms a ruby code-block. Let's understand each line.


3. get '/' do

This block is invoked when the server receives a get request on the '/' path.
4. return 'Hello World!'

This will return the 'Hello World!' string to the client.


5. end

This ends the code-block.

[3]

Introduction to Sinatra

Where is the MVC in this code?


Sinatra does not follow the MVC architecture completely; it is a VC framework. It
was mentioned earlier that the model is the data part of the application, view is the
user interface, and controller is the interconnection. Now, let's find these parts in the
preceding code:
1 require 'sinatra'
2
3 get '/' do
4
return 'Hello World!'
5 end

Here, line 1 requires just the gem. Lines 3 to 5 define a code-block that is invoked
on receiving a get request and returns a value. So here, this code-block forms the
controller. It controls what to return when a request is received.
The view is the page rendered by the browser. We do not have a separate view here
but line 4 defines the contents of the view.

How to achieve MVC using Sinatra


To achieve MVC using Sinatra, we need to pick a database framework and use it
with Sinatra. There are many database frameworks available, such as Active Record,
DataMapper, Sequel, and others. In the later chapters, we will be working with Sequel.

Sinatra application layout


As Sinatra can be used for applications that can be bare minimum or large and
complex, the application structure can grow bigger with the need.
For now, let's stick to the basic layout.
A basic Sinatra application will have a ruby file that has all the controllers defined
(for example, helloworld.rb).
If we want to have different HTML files (or different views), we should place all such
files in the views folder.
The layout is as follows:
helloworld.rb
views/

[4]

Chapter 1

Naming convention: The main application file is generally named app.rb or


website.rb.
Let's now see how to write views. Views can be written in HTML. However, there
are some gems in Ruby that make our lives easier. One of them is HAML.

HAML
HTML Abstraction Markup Language (HAML) is a templating engine that helps in
writing cleaner and simpler HTML. For example, refer to the following table:
HTML

HAML

<body>
<div id='comment'>
<form>
<input type='text'>
</form>
</div>
</body>

%body
%div#comment
%form
%input{:type => 'text'}

We can see here how HAML is simpler and neater than HTML.

Installing HAML
The following is the command to install HAML:
$ gem install haml

Using HAML in a Sinatra application


We will have two files in this case, helloworld.rb and index.haml.
The layout is as follows:
helloworld.rb
views/
index.haml
helloworld.rb
1 require 'sinatra'

[5]

Introduction to Sinatra
2 require 'haml'
3
4 get '/' do
5
haml :index
6 end
index.haml
1 %body
2
%h1
3
Hello World!

Now, let's start the application:


$ ruby helloworld.rb

After this, open the browser and point it to http://localhost:4567.

What did the code do?


You might have already guessed how this code works. We have added a new
require line to helloworld.rb. This loads the haml gem. In the controller,
we are returning a haml instead of a string.
Let's see line 5 once again:
5

haml :index

This is a ruby method call. The haml method has argument:index. The method
will look for a file named index.haml in the views folder, generate the HTML
from HAML, and return it to the client.
The following method will call the required file:
haml :<filename>

If the file does not exist in the views folder or if there are any syntax errors in
HAML, then the application will throw an error.
Let's now see index.haml:
1 %body
2
%h1
3
Hello World!

[6]

Chapter 1

We will see later that an HTML element can be defined by % in HAML and
indented blocks can be used to define child elements. So, the preceding code
will be interpreted as follows:
<body>
<h1>
Hello World!
</h1>
</body>

To Sinatra or not to Sinatra?


Every framework has its own set of pros and cons. Sinatra is not the perfect
framework for everything. Here are some of them.
Why Sinatra?

You want to be flexible and choose your own gems and libraries. Unlike
Rails, Sinatra lets the user choose whatever gems s/he wants to use.

You want a higher performance. Sinatra is lightweight and does only the
stuff that you want it to do.

You want to make a completely modular application.

You want to build an API.

You want to learn Rails.

You want to implement concurrency.

Why not Sinatra?

You feel that Rails suits your project

You have used Rails earlier and are comfortable with it

You find that the conventions in Rails are good to work with

Other frameworks
Sinatra is not the only framework being used. Here are some more that you might
have heard of:

Zend for PHP

Django for Python

Rails and Merb for Ruby


[7]

Introduction to Sinatra

ASP.NET for .NET

Catalyst for Perl

Backbone.js for JavaScript

Express for NodeJS

Summary
So, now that we have discussed what MVC is and how it is useful, you can
understand how to write your application such that the responsibilities are clearly
separated in the code. Additionally, if you are familiar with Ruby, you might have
seen how easy it is to get started with Sinatra and build a web server in minutes.
Don't worry if you could not try out the codes in this chapter as we will be covering
the same in detail soon. In the next chapter, we will be discussing the basic concepts
of Ruby. We will be discussing enough for you to get started with Ruby and Sinatra,
install Ruby and gems, and understand the data structures in Ruby. There will be
a lot for you to explore that you will find really exciting when we go further with
the book.

[8]

Get more information Learning Sinatra

Where to buy this book


You can buy Learning Sinatra from the Packt Publishing website.
Alternatively, you can buy the book from Amazon, BN.com, Computer Manuals and most internet
book retailers.
Click here for ordering and shipping details.

www.PacktPub.com

Stay Connected:

You might also like