sajad torkamani

(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"
  • 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.

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

Tagged: Ruby