DEV Community

loading...
Cover image for 49 Days of Ruby: Day 40 -- Web Frameworks: Sinatra

49 Days of Ruby: Day 40 -- Web Frameworks: Sinatra

Ben Greenberg
Rabbi turned Coder. Second Career Dev taking it one function at a time.
・2 min read

Welcome to day 40 of the 49 Days of Ruby! 🎉

For the next few days, we are going to cover the world of web frameworks in Ruby!

Today, we are starting with Sinatra.

Sinatra is a very lightweight web framework to help you get up and running.

What is a web framework, first of all?

Web frameworks take care of a lot of the overhead in building web applications for you. It allows you to focus on what you want your application to do, and less about how to do it.

When we say that Sinatra is a lightweight web framework, we mean that it automates less of that overheard. That could be helpful because it gives you more freedom to customize, but it also can mean potentially more work.

To start with a new Sinatra web app, it could be as simple as the following, taken from the project's introduction:

require 'sinatra'

get '/' do
  'Hello world!'
end
Enter fullscreen mode Exit fullscreen mode

Sinatra lets you build routes based on those HTTP verbs that we learned about earlier, as such there are get and post routes among others.

You can also build classes and blocks of code to use inside your routes, again from the introduction:

class Stream
  def each
    100.times { |i| yield "#{i}\n" }
  end
end

get('/') { Stream.new }
Enter fullscreen mode Exit fullscreen mode

In the above example, we create a new class called Stream, and we redefine the #each method. The method prints each number from 1 to 100 and a new line.

Then, we invoke the Stream class inside the get('/') route.

Spend some time exploring the Sinatra docs today and see what you can build. See you tomorrow!

Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.

Discussion (0)