NavigationContentFooter
Jump toSuggest an edit

Getting Started with Sinatra

Reviewed on 22 April 2024Published on 17 August 2018
  • ansible
  • Sinatra
  • Ruby
  • RubyGems

Sinatra is a lightweight domain-specific programming language and web application library that is used for writing web applications.

It provides a faster and simpler alternative to Ruby frameworks such as Ruby on Rails. Sinatra is written in Ruby and the code for Sinatra applications will be written in Ruby too. Sinatra routes browser requests to code that can handle those requests. Then it will render templates back to the browser as a response. For more information on Sinatra, refer to the official documentation.

To use Sinatra, we need to install three pieces of software: Ruby, RubyGems, and Sinatra. Sinatra depends on Ruby and RubyGems.

Before you start

To complete the actions presented below, you must have:

  • A Scaleway account logged into the console
  • Owner status or IAM permissions allowing you to perform actions in the intended Organization
  • An SSH key
  • An Instance running on Ubuntu Linux

Installing Ruby and RubyGems

The easiest way to install Ruby and RubyGems is using the Ruby Version Manager (RVM). RVM allows you to have multiple Rubies, with their own sets of gems (gemsets), installed.

  1. (Optional) Install nodejs, gunpg2, ruby, and curl. When using Rails, you must install Node.js, in any version you want. The asset pipeline compiler of Rails requires a JavaScript runtime. If you do not use Rails, skip this and proceed to the next step.
    apt install gnupg2 nodejs curl ruby
  2. Import the signing key to be able to verify the RVM packages downloaded in the later step.
    gpg2 --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB
  3. Install Ruby Version Manager along with a stable Ruby version.
    \curl -sSL https://get.rvm.io | bash -s stable
  4. Update your shell environment to be able to access Ruby.
    source /usr/local/rvm/scripts/rvm
  5. Confirm that Ruby is installed.
    ruby -v
    ruby 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-linux-gnu]

Installing Sinatra

Install Sinatra just as any other gem

gem install sinatra

which returns

Successfully installed sinatra-4.0.0
Parsing documentation for sinatra-4.0.0
Done installing documentation for sinatra after 1 seconds
1 gem installed

Creating your first Sinatra Application

  1. Create a new file that you can call testapp.rb.

    nano testapp.rbna
  2. Paste the following:

    require "sinatra"
    get "/" do
    "OMG, a big HELLO to my first app with Sinatra!"
    end
  3. Run your Sinatra application. The -o 0.0.0.0 parameter will bind the application to all interfaces of the server. Without this parameter, it will only be accessible from your localhost.

    ruby testapp.rb -o 0.0.0.0
    [2023-03-27 16:36:07] INFO WEBrick 1.4.4
    [2023-03-27 16:36:07] INFO ruby 2.6.10 (2022-04-12)
    == Sinatra (v3.0.4) has taken the stage on 4567 for development with backup from WEBrick
    [2023-03-27 16:36:07] INFO WEBrick::HTTPServer#start: pid=87299 port=4567

    The response tells us the port that it is running on. This time it is 4567.

  4. Point the browser to http://server-IP:4567.

Creating routes

Calls to methods like get, post, put, and delete are called routes in Sinatra. They take a path, and a block that handles a request. The request is being taken over by the web server, routed to a piece of code that handles the request and then specifies the response.

In the example above, The get '/' do part of the code is very important. It says what to do when getting a slash if there is no specified path in the URL after the port.

  1. Update the testapp.rb file to match the following:

    require "sinatra"
    get "/" do
    "OMG, a big HELLO to my first app with Sinatra!"
    end
    get '/index' do
    "Welcome to the index. It will help you find the information you need"
    end
  2. Run your little app.

    ruby testapp.rb -o 0.0.0.0

    As you notice, when adding the /index after the port number, the webpage displays the message entered in the testapp.rb file.

  3. Change the get / do route to the following:

    get '/' do
    redirect to('/index')
    end

    The redirect to sends the user to the index page. You can use redirect to move your users anywhere around your website.

Rendering templates

Embedded Ruby, also known as ERB file (Embedded RuBy file), is a file type that enables writing HTML and embedding Ruby code in it. Embedded Ruby tags are placed inside the HTML tags – Use <% %> tags to execute Ruby code or <%= %> to print out HTML.

Taking the same example as above, we will play a little more with the index. In the rb file paste the following:

get '/index' do
@songs = [{title: 'Charles Trenet, Le mer', url: "https://www.youtube.com/watch?v=qEkd1qWonj8"},
{title: 'Edith Piaf, Non je ne regrette rien', url: "https://www.youtube.com/watch?v=t6wjCcWC2aE"},
{title: 'France Gall, Poupée de cire poupée de son', url: "https://www.youtube.com/watch?v=rRva0YOVtcI"},
]
erb :default
end

If you are familiar with Ruby, the [] are used to create an array or a list, to iterate easily through.

Each item in the @songs array is called a hash and is denoted by {}.

In a hash, items are stored in key/value pairs, enabling access to a value by its key.

The last line redirects to an ERB file which automatically looks for a file called default.erb in our views folder. If you did not create this earlier, do so now.

  1. Create a new directory. We will call it views.

    mkdir views
  2. Edit the default.erb file in this directory.

    nano views/default.erb
  3. Paste the following:

    <head>
    <title>Famous French Chansons</title>
    </head>
    <body>
    <h1>A list of the most loved chansons ever</h1>
    <% @songs.each do |song| %>
    <h3> <%= song[:title] %></h3>
    <p> <a href="<%=song[:url]%>"> Video </a></p>
    <% end %>
    </body>

    Inside the first erb tags (<% %>) the each method on our @songs array is called. This enables going through ‘each’ item in the array, and then inside the pipes, each item is referred to as |song|.

    Then create a header (<h3>) tag for each song and place the song title inside the header. As each song is a hash, it is possible to refer to each value by its key (song[:title] / song[:url]).

    Open a paragraph (<p>) tag, and enclose an anchor (link) (<a>). The href attribute of the anchor tag tells where to direct the link. To redirect to the URL of the song, use another group of erb tags to get the desired information out of the @songs array and song hash.

  4. Run your app

    ruby testapp.rb -o 0.0.0.0

    which displays

Available route methods in Sinatra

Route method names correspond to HTTP 1.1 request method names to make things easier to remember.

Note

Routes are matched in the exact order that they are defined in your code, this means that the second route in the example below will never get matched because we have the same pattern further up in the code.

  • get() - Performing basic HTTP GET requests like loading pages
  • post() - Used when posting form data
  • put() - Used when updating resources
  • patch() - Similar to post(), but used when updating one field of a resource
  • delete() - Used when deleting resources
  • options() - Determine options available for an associated resource
  • link() - Link relationships between existing resources
  • unlink() - Unlink relationships between existing resources

When building a user-facing web application, you will be using get() and post() methods the majority of the time.

Docs APIScaleway consoleDedibox consoleScaleway LearningScaleway.comPricingBlogCarreer
© 2023-2024 – Scaleway