Building a Sinatra app in 5 minutes
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.
Create project directory
mkdir sinatra-demo-app && cd sinatra-demo-app
Initialise Git repo
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.
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.
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).
Visit http://localhost:4567 and you should see an HTML page with ‘Hello world’ rendered inside a
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.
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.