Creating Dynamic Web Pages Using Sinatra

Jake Zappin
Jake Zappin
Published in
6 min readOct 18, 2016

This week at the Flatiron School, we’re been learning Ruby and Sinatra to get started with some basic dynamic web programming as a stepping stone to Rails. Sinatra is a Ruby gem that allows a developer to specify how a web application or website will respond to different http requests such as GET, POST, etc. and routes (the part of the URL after the domain, like / or /user or /user/post/123).

In this post, I’ll be walking us through how to create a basic “hello world” application using Sinatra. The application will offer a greeting to the user and can be customized based on the URL route.

Sinatra Setup

Sinatra is a Ruby gem. In order to install it, run “install sinatra” in your terminal window.

Also, in your terminal window create a new directory for this project, e.g., “mkdir hello_world.rb.”

After opening “hello_world.rb” we want our application to have access to the Sinatra library. In order to do this, we add “require “sinatra”” at the top of the file so that our application can access the Sinatra libraries. Now, we’re ready to create our Hello World App!

Writing Our “Hello, World!” App

We just want our app to print out “Hello, world!” in the web browser when a user navigates to the domain’s base or root ( / ) directory. The “root route” is the domain name without any path at the end (like http://your_domain.com/).

Using Sinatra, we do this by calling a method that corresponds to the HTTP request type we want to recognize (in this case, GET), and we pass it the route as an argument (in this case, “/”).

The GET method takes a path as an argument and will route the user to that path. Within the GET method we specify a black, and the return value of the block is sent as a response to the web browser. Usually, this will be a string containing HTML code.

Here’s how our simple “Hello World!” application should look like get Sinatra:

picture1

We can test it out in our browser by running ruby hello_world.rb. This will launch a local server using port 4567 of our computer so we can load the app in our browser. Navigate to http://localhost:4567 in your browser and you should see “Hello, World!”

Congratulations! We built our first Sinatra web app!

Adding URL Parameters

We can also change the greeting by printing different text based on the URL route that the user types in. This only take a simple adjustment to our code above.

Picture2.png

Sinatra allows us to specify parameters that take a value typed within the URL by the user. Parameters are specified with a :symbol in the route. So we could define a new route to dynamically change the greeting based on the URL:

We’ve added a couple of things here to dynamically change the output on the page. The symbol :name in the route is like a variable. Whatever is typed in the URL after /hello/ will automatically be added by Sinatra to a hash, a data structure, called params. On the second line, we’re assigning that string from the params hash to an instance variable called @hello_name. Finally, we just include that name in a string through string interpolation as the block’s return value, which is then displayed in the browser.

Let’s try it out now.

Note that every time we change the Ruby file, we’ll need to restart the server. Use CTL-c in the terminal to quit the server, and run ruby hello_sinatra.rb again to relaunch the server with the updated Ruby file. In the browser, type http://localhost:4567/hello/Jake to load the page. If everything’s working correctly, we’ll see “Hello, Jake!” in plain text. Now, if we type http://localhost:4567/hello/Kristen we should see “Hello, Kristen!” in the browswer.

We’re dynamically generating content based on the URL!

Adding Multiple Parameters

From here, we can add additional parameters to our routes by adding additional symbols. Let’s update the program to output the name and the greeting based on the URL:

Picture3.png

Reload the server and test it out in your browser with http://localhost:4567/goodbye/Kevin. We’ve created a dynamic application based on the user’s input to the http routes!

Multiple Routes

It is important to note that Sinatra reads the routes in the order they’re written in your Ruby file. As soon as it finds a route that matches the request sent to the server, it executes that route. This means that routes should be listed in order from most specific to least specific. For example:

Picture4.png

ERB

Now that we’re delivering dynamic content, we’ll probably want to format it using HTML. But we don’t want to start mixing a bunch of HTML code into our Ruby logic. Sinatra has a solution: it works with embedded ruby files or “ERB”.

ERB is, in this case, simply HTML code with two additional pieces of syntax: <% … %> and <%= … %>. This allows us to embed Ruby code into an HTML page by inserting it between the tags.

There is one simple difference between these tags:

  • The <% … %> tags execute any Ruby inside of them, but do not output the return value to the page.
  • The <%= … %> tags execute the Ruby code inside of them, and also perform string interpolation on the return value of the ruby code. This is printed to the page.

Using ERB

To use an ERB template, we just add it to the block and use a symbol to reference the ERB file:

Picture6.png

The line erb :greeting tells Sinatra to look in the views/ folder — the default for all template and layout files — for a file named greeting.erb. After processing the embedded Ruby, the server sends the output of that file to the browser.

Let’s create ERB file for this route: views/hello.erb. And, luckily, we can access our instance variables from within the ERB file as shown below:

Picture7.png

Future Topics

Sinatra has an additional templating feature called “layouts,” which allows us to separate out some of the boilerplate HTML from our template files, to avoid repetition.

We’ve also only just scratched the surface here because Sinatra also supports responding to other HTTP requests such as POST which allows the user to send information to the server via a web form. This allows us to collect and store data inputted by the user.

We may investigate these features in other blog posts.

Additional Resources

--

--