sajad torkamani

What is Sinatra?

Sinatra is a Ruby micro web framework that helps you quickly build a back-end. It is comparable to Python’s Flask or Node.js’s Express.

Let’s get a taste for Sinatra by building a simple application that displays a random joke on each page visit or refresh. Here’s the link to source code.

Setup project

Create project directory:

mkdir sinatra-demo-app && cd sinatra-demo-app

Initialize Git repo:

git init

Create Gemfile:

source 'https://rubygems.org'
gem "sinatra", "~> 2.0"
gem "rerun", "~> 0.13.0"
gem "httparty", "~> 0.18.1"
  • sinatra – the gem that contains the actual Sinatra web framework.
  • rerun – used in order to restart Sinatra whenever we make any code changes.
  • httparty – lightweight Ruby HTTP client that we’ll use later.

Install gems:

bundle install

Create first route

Create a minimal app.rb in your project root.

require 'sinatra'
get '/' do
  'Hello world'
end

Inside a terminal, run:

rerun 'ruby app.rb'

Visit http://localhost:4567 and you should see ‘Hello world’.

Thanks to the rerun gem, any changes you make to app.rb should restart Sinatra and apply your changes. Feel free to change ‘Hello world’ to something else to see your changes reflected.

Render ERB template

Sinatra makes it a breeze to render dynamic ERB templates. Change app.rb to the following:

require 'sinatra'
get '/' do
  erb :home
end

This will render a views/home.erb file. You can also make use of layouts and partials for more advanced use cases (see docs for more info).

Create views/home.erb:

<h1>Hello world</h1>

Visit http://localhost:4567 and you should see an HTML page with ‘Hello world’ rendered inside a h1 tag.

Passing data to views

Let’s spice things up a little bit by integrating an open-source Joke API (seems to be down at the moment) and display a random joke on the page.

We’ll use the httparty gem we added earlier in order to call this API.

require 'sinatra'
require 'httparty'
get '/' do
  @joke = HTTParty.get('https://official-joke-api.appspot.com/random_joke')
  erb :home
end

Sinatra will render the views/home.erb template within the same context as the route handler which means you can access the @joke instance variable inside our template.

<h3><%= @joke['setup'] %></h3>
<h2><%= @joke['punchline'] %></h2>

Visit http://localhost:4567 and you should see a random joke each time.

Leave a comment

Your email address will not be published. Required fields are marked *