The Object Storage release is imminent. Get your access to the preview and discover it now. 🚀

Help


Community tutorials and documentations

Getting Started with Sinatra

Sinatra Overview

Sinatra is a lightweight web application library and domain-specific language that provides a faster and simpler alternative to Ruby frameworks such as Ruby on Rails. Sinatra is written in the Ruby programming language and the code that you’re going to write will be written in Ruby too. Sinatra does two things. It routes browser requests to code that can handle those requests and then from there 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 best way to install Ruby and RubyGems is with Ruby Version Manager (RVM). RVM allows you to have multiple Rubies installed, with their own sets of gems (gemsets).

1 . (Optional) Install nodejs curl. If you are using Rails, then you must install Node.js. This is because Rails’s asset pipeline compiler requires a Javascript runtime. The Node.js version does not matter. If you do not use Rails then you can skip to the next step.

apt install nodejs curl

2 . Import the signing key to be able to verify the RVM packages downloaded in the later step

curl -sSL https://rvm.io/mpapis.asc | gpg --import -
gpg: keybox '/root/.gnupg/pubring.kbx' created
gpg: key 3804BB82D39DC0E3: 47 signatures not checked due to missing keys
gpg: /root/.gnupg/trustdb.gpg: trustdb created
gpg: key 3804BB82D39DC0E3: public key "Michal Papis (RVM signing) <mpapis@gmail.com>" imported
gpg: Total number processed: 1
gpg:               imported: 1
gpg: no ultimately trusted keys found

3 . Install Ruby Version Manager along with a stable Ruby version

curl -sSL https://get.rvm.io | bash -s stable --Ruby

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.3
Parsing documentation for sinatra-2.0.3
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

In Sinatra calls to methods like get, post, put, and delete are called routes. They take a path, and a block that handles a request. The request is being picked up by the webserver, and then routed to a piece of code that handles the request, and specifies the response.

In the example above, The get ‘/’ do part of the code is very important. It is telling us what to do when we get a slash – or, more specifically, if there is no specified path in the URL after the port number.

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 automatically sends the user to the index page. You can use ‘redirect’ to move your users anywhere around your website that you like.

Rendering Templates

Embedded Ruby, also known as ERB file (an Embedded RuBy file), is a file type that allows us to write HTML and embed Ruby code in it. Embedded Ruby tags go inside the html tags – we use <% %> tags to execute Ruby code or <%= %> to print something to 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: 'Fly Me To The Moon', url: "https://www.youtube.com/watch?v=mQR0bXO_yI8"},
            {title: 'New York, New York', url: "https://www.youtube.com/watch?v=btFfXgUdIzY"},
            {title: 'My Way', url: 'https://www.youtube.com/watch?v=6E2hYDIFDIU'},
            {title: 'The Way You Look Tonight', url: 'https://www.youtube.com/watch?v=h9ZGKALMMuc'},
            {title: 'I Get A Kick Out Of You', url: 'https://www.youtube.com/watch?v=wSrHvNr8QQQ'}]
  erb :default
end

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

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

In a hash items come in key/value pairs and so you can access a value by its key.

The last line in our route is one of the very handy things about Sinatra. It is essentially redirecting to an ERB file which automatically looks for a file called default.erb in our views folder. If you didn’t create this earlier, to 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>Sinatra Songs</title>
</head>
<body>
<h1>Sinatra Songs</h1>
<% @songs.each do |song| %>
    <h3> <%= song[:title] %></h3>
    <p> <a href="<%=song[:url]%>"> Video </a></p>
<% end %>
</body>
Inside the first erb tags (<% %>) we are calling the ‘each’ method on our @songs array. That means we are going to go through ‘each’ item in the array, and then inside the pipes we say we are going to refer to each item assong.

The next line we create a header (<h3> tag) for each song and inside the header we put the the song title. Because each song is actually a hash we can refer to each value by its key eg. song[:title] or song[:url].

After this we create a paragraph (<p> tag), and enclose a link or anchor tag (). The href property of the anchor tag tells it where to direct the link, and we want it to go to the url of the song, so we’ll use another set of erb tags to get that information out of our @songs array and song hash.

4 . Run your little app

ruby testapp.rb -o 0.0.0.0

which displays

firstsongs

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.