Sinatra at it’s Core

Day Clawtel
2 min readApr 8, 2022

Sinatra can seem intimidating at first, but when you strip it down to its core, Sinatra can make your life as a programmer much easier. Sinatra is based on Rack and helps it be nimble and fit into numerous applications, including Rails. Multiple big named companies use Sinatra worldwide and knowing the basics is very valuable.

Sinatra is nothing more than some pre-written methods that we can include in our applications to turn them into Ruby web applications.

Unlike Ruby on Rails, which is a Full Stack Web Development Framework that provides everything needed from front to back, Sinatra is designed to be lightweight and flexible. Sinatra is designed to provide you with the bare minimum requirements and abstractions for building simple and dynamic Ruby web applications.

In addition to being a great tool for certain projects, Sinatra is a great way to get started in web application development with Ruby and will prepare you for learning other larger frameworks, including Rails.

Basic Sinatra Applications

First, make sure Sinatra is installed by running gem install sinatra in your terminal.

The simplest Sinatra application would be:

File: app.rb

require 'sinatra'class App < Sinatra::Base
get '/' do
"Hello, World!"
end
end

You could start this web application by running rackup app.rb. You'll see something similar to:

If you start this application and navigate to http://localhost:9292 you’ll see “Hello, World!” in your browser. Go back to your terminal running the Sinatra application and stop it by typing CTRL+C. You should see:

Modular Sinatra Applications

Web applications, even simple Sinatra ones, tend to require a certain degree of complexity. For example, your application might have multiple routes, route-handlers, and configuration. To handle this, Sinatra is more commonly used through the Modular Sinatra Pattern (over the classical, single file app.rb pattern).

config.ru

The first new convention this pattern introduces is a config.ru file. The purpose of config.ru is to detail to Rack the environment requirements of the application and start the application.

A common ‘config.ru’ might look like:

File: config.ru

require 'sinatra'require_relative './app.rb'run App

In the first line of config.ru we load the Sinatra library. The second line requires our application file, defined in app.rb. The last line of the file uses run to start the application represented by the ruby class App, which is defined in app.rb.

The class name we defined in our application controller (app.rb) is just a normal Ruby class. We could have named it MyFunnyApp:

require 'sinatra'class App < Sinatra::Base
get '/' do
"Hello, World!"
end
end

If this was our class name, we would need to change config.ru to run the appropriate class:

run App

This is the most basic Sinatra application structure and Controller Classes and booted via the config.ru Rack convention.

Happy coding!!!

--

--