Getting Started with Sinatra

Sinatra Overview

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

In order to use Sinatra, we’re going to need three pieces of software installed: Ruby, RubyGems, and Sinatra. Sinatra depends on having Ruby and RubyGems.

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 and curl. When using Rails, is is required to install Node.js. The asset pipeline compiler of Rails requires a Javascript runtime. The version of Node.js being installed does not matter. If you do not use Rails, skip this and proceed to the next step.

apt install nodejs gunpg2 curl

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 you shell environment to be able to access Ruby

source /usr/local/rvm/scripts/rvm

5 . Confirm that Ruby is installed

ruby -v
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux]

Installing Sinatra

Install Sinatra just as any other gem

gem install sinatra

which returns

Successfully installed sinatra-2.0.5
Parsing documentation for sinatra-2.0.5
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.rb

2 . Paste the following

require "sinatra"

get "/" do
  "OMG, a big HELLO to my first app with Sinatra!"
end

3 . Run your little app. The parameter -o 0.0.0.0 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
[2018-08-17 09:40:22] INFO  WEBrick 1.4.2
[2018-08-17 09:40:22] INFO  ruby 2.5.1 (2018-03-29) [x86_64-linux]
== Sinatra (v2.0.3) has taken the stage on 4567 for development with backup from WEBrick
[2018-08-17 09:40:22] INFO  WEBrick::HTTPServer#start: pid=31619 port=4567

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

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

firstapp

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 is telling 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.

firstindex

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 embed 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 the access to a value by its key.

The last line is redirecting 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 a 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 reffered as |song|.

Then create a header (<h3>) tag for each song and place the song title inside the header. As each song is actually a hash, it is possible 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

songs

Available Routes 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 second route in the below example will never get matched because we have the exact 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 user facing web application, you’ll be using get() and post() methods the majority of the time.

Discover a New Cloud Experience

Deploy SSD Cloud Servers in seconds.