Sep 16, 2015
Table of contents:
In the world of Ruby there are a number of web frameworks to choose from. Sinatra is a very popular “micro-framework” for building web applications.
This is perfect for building simple websites, applications or APIs that don’t require the weight or functionality of a framework like Ruby on Rails.
In today’s tutorial we will be looking at getting started with Sinatra to build a simple website.
As we’ve seen over the last couple of weeks with Rake and Rack, like all good things Ruby, you can install Sinatra as a gem:
$ gem install sinatra
If you already have your Ruby environment set up correctly, this should just work and you will have Sinatra installed in just a few minutes.
Now that we have Sinatra installed we can go ahead and create our first Sinatra application.
Create a new file called app.rb
with the following contents:
require 'sinatra'
get '/' do
'Hello World!'
end
First we need to require sinatra
into this application.
Next we define the "/"
route, which will be the root of the application. This route will accept a GET
request and return a body of "Hello World!"
.
Now if you run the following command in Terminal and then go to https://localhost:4567
in your browser you should see the correct response:
$ ruby app.rb
To define routes for other HTTP methods you can simply use the following syntax:
post 'posts' do
# Create a new Post
end
put 'users/:id' do
# Update the user
end
delete 'tags/:id' do
# Delete the tag
end
An important part of any web application is accepting URL parameters. For example, you might want to have vanity URLs for your user’s profiles.
Sinatra makes it really easy to accept URL parameters and use them in your application:
require 'sinatra'
get '/:name' do
"Hello #{params['name']}!"
end
Now if you go to https://localhost:4567/you_name
you should be greeted by the application.
If you are building an API with Sinatra, you might be able to get away with having everything in one file. However, if you are building a website, you will want to have view files for each page.
To use view files, create a new directory called views
and then create a new file called index.erb
:
<h1>Hello <%= @name %></h1>
Next, update your route definition to look like this:
get '/:name' do
@name = params[:name]
erb :index
end
In this example I’m simply grabbing the name
from the params
hash and then calling the index
template.
Now if you restart the application and refresh your browser you should see the HTML from the index.erb
view file.
This was only a brief introduction to Sinatra, but hopefully you can see how easy it makes building simple websites, applications or APIs.
It’s often the case that you need to provide a server backend for an application or service, but you don’t need the overhead of a fully blown web framework.
This is the perfect opportunity to use a micro-framework like Sinatra!