O'Reilly logo

Learning Sinatra by Manoj Sehrawat, Sudeep Agarwal

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Writing your first Sinatra application

Let's see how to write a bare minimum Sinatra application. We will open a new file and write the following code:

1 require 'sinatra' 
2 get '/' do
3   return 'Hello World!'
4 end

Save the file with a .rb extension (say, helloworld.rb) and execute this on the command line:

$ ruby helloworld.rb

This will interpret the code and start the built-in server.

Now, we open the browser and point it to http://localhost:4567.

What did the code do?

1.require 'sinatra'

This tells the Ruby interpreter to load the Sinatra gem:

3 get '/' do
4   return 'Hello World!'
5 end

This forms a ruby code-block. Let's understand each line.

3. get '/' do

This block is invoked when the server receives a get request on the '/' path.

4. return 'Hello World!' ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required