Learning Sinatra - Sudeep Agarwal - E-Book

Learning Sinatra E-Book

Sudeep Agarwal

0,0
26,39 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Design and deploy your own web application in minutes using Sinatra

About This Book

  • Exploit Sinatra to design a web application
  • Integrate external, internal, and inline CSS and use some popular CSS frameworks
  • Deploy an application onto your own server or on a cloud application platform

Who This Book Is For

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.

What You Will Learn

  • 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 front-end 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

In Detail

Sinatra is a Ruby framework that is widely used in the 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 brand-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 back-end, design and customize the front-end layout, and utilize the innovative and user-friendly features of ORMs. By sequentially working through the steps in each chapter, you will quickly master Sinatra's features 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.

Style and approach

This book takes a step-by-step approach to Sinatra and explains it in a conversational and easy-to-follow style. A simple project is used as a base to explain each topic. The code and screenshots included add to the ease of learning.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 182

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Learning Sinatra
Credits
About the Authors
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Introduction to Sinatra
What is MVC?
Installing Sinatra
Writing your first Sinatra application
Where is the MVC in this code?
How to achieve MVC using Sinatra
Sinatra application layout
HAML
Installing HAML
Using HAML in a Sinatra application
What did the code do?
To Sinatra or not to Sinatra?
Other frameworks
Summary
2. Introduction to Ruby
Installation
For Linux users
For Windows users
IRB
Installation
Using IRB
Ruby data types
Strings
Numbers
Symbols
Arrays
Array.each
Array.include
Array.map
Array.select
Hashes
Hash.each
Hash.include?
Hash.keys
Hash.select
Code blocks
Classes and objects
Defining modules and classes
Constructors
Class methods and instance methods
Defining methods
Methods with no arguments
Methods with a fixed number of arguments
Arguments with default values
Methods with variable-length argument lists
Private, protected, and public methods
Control structures in Ruby
if-elsif-else-end
unless..end
Ternary operator
Inline conditions
Case
Operators
eql?
equal?
Loops
while-end
until-end
Fixnum.times
for..in
Controlling the flow of iterations
Exception handling
Summary
3. Hello World
Getting started
The application
The idea
The file structure
app.rb
config.ru
Gemfile
Bundler
Gem install bundler
Bundle install
lib/routes.rb
What is a route?
The code
app.rb
Breaking down the code
config.ru
How the code works
Gemfile
Starting the application
Features
Users
Lists
Object Relationship Mapper
Designing views
Summary
4. Modeling the Backend
What is Object-relational mapping
When to use an ORM
How to define migrations
The users table
The lists table
The items table
The permissions table
The logs table
How to define models
The User model
The List model
Permission Model
The Log model
How to run migrations
What are the responsibilites of the models?
The User model
The List model
The Item model
The Permission model
The Log model
Summary
5. Handling HTTP Requests
Understanding the application file – app.rb
Writing app.rb
Writing routes for the responsibilities of the application
Showing a page for all the existing lists
Showing a page to create a new list
Handling the saving of a new list
Showing a page to edit a list
Handling the updating of a list
Handling the changing of permissions on a list
Showing a page for signup
Saving the new user data
Showing a page for login
Handling user login
Sending the data and designing the views
Showing a page for all the existing lists
Showing a page to create a new list
Handling the saving of a new list
Showing a page to edit a list
Handling the updating of a list
Changing permissions on a list
Showing a page for signup
Saving the new user data
Showing a page for login
Handling user login
Handling user logout
Understanding before and after blocks
Summary
6. Designing the Frontend Layout
Understanding Twitter Bootstrap and jQuery
Writing haml templates
Writing layout.haml
Writing signup.haml
Summary
7. Handling User Data
Creating forms
A quick overview of the HTML form tag
Writing new_list.haml
Handling data in the backend
Validations
Frontend Validations
Backend Validations
Summary
8. Connecting to a Database
Connecting to a database
An interactive console
How to use an ORM
The Sequel model
Some useful model class methods
db_schema
columns
create
find_or_create
def_column_alias
first, first!, and last
with_pk and with_pk!
finder
no_primary_key
set_primary_key
restrict_primary_key and unrestrict_primary_key
set_allowed_columns
subset
Useful model instance methods
values or to_hash
errors and valid?
exists?
changed_columns
refresh or reload
modified?
new?
modified!
save
delete
destroy
set
set_all
update
update_all
Hooks or callbacks
Associations
Eager loading
Joins with associations
Summary
9. Authentication and Authorization
Using sessions in Sinatra
What are sessions?
How does it work?
Using the session variable
Enabling a session
Advanced options
Methods of the session object
Handling authentication using session
What is authentication and authorization?
Building authentication
Building authorization
Summary
10. Deploying the App
Deployment
What is Heroku?
Getting started with Heroku
Creating an account
Setting up the command-line interface
Creating a Heroku app
Setting up an app for Heroku
Adding Ruby to Gemfile
Adding Procfile
Using SQL on Heroku
Summary
Index

Learning Sinatra

Learning Sinatra

Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: April 2016

Production reference: 1220416

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-84951-930-4

www.packtpub.com

Credits

Authors

Sudeep Agarwal

Manoj Sehrawat

Reviewer

Ken Taylor

Commissioning Editor

Jonathan Titmus

Acquisition Editor

Nadeem Bagban

Content Development Editor

Onkar Wani

Technical Editor

Danish Shaikh

Copy Editor

Tasneem Fatehi

Project Coordinator

Bijal Patel

Proofreader

Safis Editing

Indexer

Mariammal Chettiyar

Production Coordinator

Arvindkumar Gupta

Cover Work

Arvindkumar Gupta

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

This book would not have been possible without the constant support of my family, friends, and peers. I thank everyone for keeping me motivated and helping me with their suggestions. This book is dedicated to each one of them.

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.

I would like to thank several people who helped and supported me in making this book a reality. First, I want to thank my family and fiancé for having the patience with me for taking yet another challenge, which decreases the amount of time I can spend with them.

I must mention that the PECT team is responsible for having me on the team and giving me the opportunity to write this book. I want to thank three of our editors and technical reviewers who worked on this book.

Finally, thanks to the Sinatra and Ruby community!

About the Reviewer

Ken Taylor has worked in software development and technology for over 15 years. During the course of his career, he has worked as a systems analyst on multiple software projects in several industries as well as U.S. government agencies. He has successfully used Ruby (and DSLs like Sinatra) on multiple projects. Ken previously reviewed the books RabbitMQ Cookbook and RabbitMQ Essentials by Packt Publishing. He is an organizer for Google Developer Groups (GDG) and a member and speaker for both 757 Ruby users and the Hampton Roads .NET (HRNUG) users groups. Ken holds an A.S. in computer science from Paul D. Camp Community College and was awarded a U.S. patent for a real estate financial software product. He is currently working as an independent consultant for Onixle LLC. He lives in Virginia Beach, Virginia with his lovely wife, Lucia, and his two sons, Kaide and Wyatt.

I would like to thank my family for being a constant support in all of my endeavors.

www.PacktPub.com

eBooks, discount offers, and more

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

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, HandlingHTTP 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.

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.

What you need for this book

A basic knowledge of tools and technologies used to write web applications such as HTML, databases, and others. Previous knowledge of any other dynamic language such as Python might help you, but the book covers an introduction to Ruby for first-timers.

Who this book is for

This book will be useful to someone who wants to write lightweight web applications of any size on their own. Someone who wants to move to Ruby-based frameworks from other languages would also find this book interesting.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We can include other contexts through the use of the include directive."

A block of code is set as follows:

[default] exten => s,1,Dial(Zap/1|30) exten => s,2,Voicemail(u100) exten => s,102,Voicemail(b100) exten => i,1,Voicemail(s0)

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

[default] exten => s,1,Dial(Zap/1|30) exten => s,2,Voicemail(u100) exten => s,102,Voicemail(b100) exten => i,1,Voicemail(s0)

Any command-line input or output is written as follows:

# cp /usr/src/asterisk-addons/configs/cdr_mysql.conf.sample /etc/asterisk/cdr_mysql.conf

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Clicking the Next button moves you to the next screen."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. 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-ControllerHow Sinatra is an MVC frameworkWhen to use Sinatra and when not to use itOther 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).

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

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.

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).