Building a Sinatra app in 5 minutes

(View the final app)

Sinatra is a micro web framework for Ruby that provides us with the bare basics to quickly spin up 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 will display a random joke each time we visit the home page.

Project setup

Create project directory

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

Initialise Git repo

git init

Create Gemfile

source 'https://rubygems.org'

gem "sinatra", "~> 2.0"
gem "rerun", "~> 0.13.0"
gem "httparty", "~> 0.18.1"

Run bundle install to install the gems.

Creating our 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’.

Because we’re using rerun, any changes we make to app.rb should restart Sinatra and apply our changes. Feel free to change ‘Hello world’ to something else to see your changes reflected.

Rendering views

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

Let’s 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 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 we 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.

Conclusion

With very little effort, we were able to have a pretty functional web app that includes routing, templating and integration with a third-party API.

You can view the full source code for this example app here.

Sajad Torkamani

Hello! My name is Sajad. I’m a software developer at Nationwide and an aspiring entrepreneur. Originally from Afghanistan, I moved to London at an early age and have been living here for the past 20 years.

This is my personal website where I blog mostly about programming with occasional thoughts on a bunch of other things. I write mainly for my own benefit as I find that writing helps clarify my otherwise very confused thoughts.

Get in touch: sajadtorkamani1@gmail.com