Chapter 17. Web Development: Sinatra

Sinatra, first released two years after Rails in 2007, was a reaction against the growing number of complicated web frameworks full of magical code. Frameworks like Rails provided a lot of functionality in the box, but if you didn’t need the functionality, their overhead was expensive. This led to the development of microframeworks like Sinatra.

Sinatra is tiny and modular. It does not have the batteries included. It is meant to simply do a few things really well with as little code as possible. Sinatra is built to get out of your way and not overburden you with complexity. To understand exactly how slim Sinatra is as a web framework, let’s look at a simple “Hello World” example:

require 'sinatra'

get '/hi' do
  "Hello World!"
end

Just one file. In Rails, a simple “Hello World” takes 19 Ruby files and 4 HTML templates. There are tradeoffs, of course. If you need to generate complex web applications, the helpers and templates that Rails provides come in very handy. On the other hand, if you are trying to build a simple REST API, a Rails app may be overkill.

It comes back to picking the right tool for the right purpose. In some cases the right tool will be Ruby on Rails. In other cases, it will be a microframework like Sinatra. There have been dozens of microframeworks inspired by Sinatra in dozens of languages. In PHP, you have Glue, Laravel, and Slim. In Node, you have Express. In Python, there is Bottle and Flask. In Java, there is Spark and ...

Get Ruby Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.