15
Community Experience Distilled Design and deploy your own web application in minutes using Sinatra Learning Sinatra Sudeep Agarwal Manoj Sehrawat Free Sample

Learning Sinatra - Sample Chapter

Embed Size (px)

Citation preview

Page 1: Learning Sinatra - Sample Chapter

C o m m u n i t y E x p e r i e n c e D i s t i l l e d

Design and deploy your own web application in minutes using Sinatra

Learning SinatraS

udeep Agarw

al Manoj S

ehrawat

Learning Sinatra

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.

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.

Who this book is written forLearning Sinatra is a great place to start your fi rst Sinatra application. It doesn't matter whether you have written a web application before or not, though some basic knowledge of programming is essential.

$ 29.99 US£ 19.99 UK

Prices do not include local sales tax or VAT where applicable

Sudeep AgarwalManoj Sehrawat

What you will learn from this book

Install and set up Ruby and Sinatra

Work with layouts and template routes

Extend the code to include CSS in different ways

Create projects and understand MVC

Design the frontend with Twitter Bootstrap

Use the MySQL/SQLite gem to communicate with databases

Implement sessions that can be used across multiple pages

Utilize the innovative and user-friendly features of ORMs

Learning Sinatra

P U B L I S H I N GP U B L I S H I N G

community experience dist i l led

Visit www.PacktPub.com for books, eBooks, code, downloads, and PacktLib.

Free Sample

Page 2: Learning Sinatra - Sample Chapter

In this package, you will find: The authors biography

A preview chapter from the book, Chapter 1 'Introduction to Sinatra'

A synopsis of the book’s content

More information on Learning Sinatra

Page 3: Learning Sinatra - Sample Chapter

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 fi nishing 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 ORMs—Ruby Object Mapper.

Page 4: Learning Sinatra - Sample Chapter

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 fi rst full stack holiday marketplace that connects travelers with verifi ed 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.

Page 5: Learning Sinatra - Sample Chapter

PrefaceThis 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 confi dence to write more apps by yourself.

What this book coversChapter 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.

Page 6: Learning Sinatra - Sample Chapter

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 fi lling 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 confi gure 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.

Page 7: Learning Sinatra - Sample Chapter

[ 1 ]

Introduction to SinatraSinatra 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 fl exibility. 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).

Page 8: Learning Sinatra - Sample Chapter

Introduction to Sinatra

[ 2 ]

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 SinatraSinatra is just another gem and there is no special way to install it. We use the gem install comma nd:

$ 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

Page 9: Learning Sinatra - Sample Chapter

Chapter 1

[ 3 ]

Writing your fi rst Sinatra applicationLet's see how to write a bare minimum Sinatra application. We will open a new fi le and write the following code:

1 require 'sinatra' 2 get '/' do3 return 'Hello World!'4 end

Save the fi le 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 '/' do4 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.

Page 10: Learning Sinatra - Sample Chapter

Introduction to Sinatra

[ 4 ]

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 fi nd these parts in the preceding code:

1 require 'sinatra'23 get '/' do4 return 'Hello World!'5 end

Here, line 1 requires just the gem. Lines 3 to 5 defi ne 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 defi nes the contents of the view.

How to achieve MVC using SinatraTo 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 layoutAs 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 fi le that has all the controllers defi ned (for example, helloworld.rb).

If we want to have different HTML fi les (or different views), we should place all such fi les in the views folder.

The layout is as follows:

helloworld.rbviews/

Page 11: Learning Sinatra - Sample Chapter

Chapter 1

[ 5 ]

Naming convention: The main application fi le 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.

HAMLHTML 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 HAMLThe following is the command to install HAML:

$ gem install haml

Using HAML in a Sinatra applicationWe will have two fi les in this case, helloworld.rb and index.haml.

The layout is as follows:

helloworld.rbviews/ index.haml

helloworld.rb1 require 'sinatra'

Page 12: Learning Sinatra - Sample Chapter

Introduction to Sinatra

[ 6 ]

2 require 'haml'34 get '/' do5 haml :index6 end

index.haml1 %body2 %h13 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 fi le 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 fi le:

haml :<filename>

If the fi le 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 %body2 %h13 Hello World!

Page 13: Learning Sinatra - Sample Chapter

Chapter 1

[ 7 ]

We will see later that an HTML element can be defi ned by % in HAML and indented blocks can be used to defi ne 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 frameworksSinatra 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

Page 14: Learning Sinatra - Sample Chapter

Introduction to Sinatra

[ 8 ]

• ASP.NET for .NET• Catalyst for Perl• Backbone.js for JavaScript• Express for NodeJS

SummarySo, 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 fi nd really exciting when we go further with the book.