Screencasts

Introduction to Sinatra

Show Notes

Welcome to the Introduction to Sinatra screencast. You may also be interested in our Introduction to Haml screencast, as we will be using some Haml in this video.

You might be surprised to find out that if you search on Google for “Sinatra”, the first result is not Ol’ Blue Eyes, but is instead a web application framework for rapidly building web applications in Ruby.

This screencast will show you how to get started!

Links

What you'll learn

  • The basics of routing in Sinatra
  • How to use inline and file templates and views
  • How to use variables
  • How to use named parameters in your routes and code

Script

Welcome to the Introduction to Sinatra screencast. You may also be interested in our Introduction to Haml screencast, as we will be using some Haml in this video.

You might be surprised to find out that if you search on Google for “Sinatra”, the first result is not Ol’ Blue Eyes, but is instead a web application framework for rapidly building web applications in Ruby.

Sinatra is a domain-specific language, or DSL. This means it is designed from the ground up to build web applications with minimal effort.

Installing Sinatra

To install Sinatra, open a terminal window and type gem install sinatra. You may need to use sudo for this.

Create a new file called app.rb, and type require 'rubygems' on the first line, and then require 'sinatra' on the next. Back in the console, run ruby app.rb, and you’ll see that a WEBrick web server has spun up on port 4567.

When we visit the http://locahost:4567 we see Sinatra telling us it doesn’t know how to respond to this request. It also gives us some "Hello World" code. Let’s copy and paste this in to our app.rb file. When we refresh the page, we still see the same message as before. That’s because once your Sinatra app is running, it caches the code in memory.

So we need to press control + C in the terminal window to stop the Sinatra application.

So now when we restart the server again and visit the url in our browser, we see "Hello World".

Sinatra’s core syntax deals with URL matching for the HTTP methods, GET, POST, PUT and DELETE. A route is defined by matching an HTTP method with a URL pattern. Each route has an associated block of code that is executed when a request is matched.

The code supplied by the Sinatra error page we saw a moment ago is a get request, matching the root path (/). It returns a string "Hello World" that gets passed into the body of the response for browsers to render. In some cases you may want to just output a string, but most likely you’ll want to use templates and views.

get '/' do
    "Hello World"
end

Templates & Views

Lets say we’re setting up a simple site with an index, about, and contact page.

We’d set this up by creating 3 routes '/' for the index, '/about' for the about page, and '/contact' for the contact page.

Sinatra allows you to use a wide variety of templating languages. We’re going to use Haml in this case, so lets require 'haml' at the top, and then install it in the console by typing gem install haml.

Then at the end of each block you’ll want to add haml followed by the name of your template. So for index, the line would be haml :index and so forth.

get '/' do
    haml :index
end

get '/about' do
    haml :about
end

get '/contact' do
    haml :contact
end

So, where are the views and templates stored? There are two common ways to store them. The first way is to use in-line templates. You’ll find this commonly used in really simple, small apps. This is where you declare the end of your source code with __END__, then two @ symbols, followed by the name of your view, then the contents of your view.

get '/' do
    haml :index
end

get '/about' do
    haml :about
end

get '/contact' do
    haml :contact
end

__END__

@@index
%html
  %body
    %h1 Welcome to Our Site

@@about
%html
  %body
     %h1 About Our Site

@@contact
%html
  %body
    %h1 Contact Us

If we’re going to have several views, it’s best to use a layout for the surrounding markup. To do this, define a layout by adding two @ symbols, followed by the word layout.

All we need to do then is add any site-wide markup here, and remove all the duplicate markup from the views. The yield line represents where each view file will be rendered within the layout.

And here’s how our example looks with the duplicate code removed.

..

__END__

@@layout
%html
  %body
     = yield

@@index
%h1 Welcome to Our Site

@@about
 %h1 About Our Site

@@contact
 %h1 Contact Us

When we stop and re-start our Sinatra application, we can now see that our pages are rendering fine.

The second way to include views is to add a views folder. A view file’s name should be the same as the reference passed to haml, with the .haml extension. If you’re using a different templating language, the extension will of course be different.

So since we’re using Haml, all of our files will end with .haml. So in our views folder we have a layout.haml, index.haml, contact.haml and about.haml. Each file contains the markup that would have been in-line for that page in the previous example.

Variables

So far we’ve only created a fairly static site. What if we want to add variables? Let’s say we want a different title for each page. To do this, we include an instance variable in each route block. Let’s call it @title , and then set whatever we want as the title for that route block. We’ll do this for each page.

...
get '/' do
    @title = "Home Page"
    haml :index
end

get '/about' do
    @title = "About Us"
    haml :about
end

get '/contact' do
    @title = "Contact Us"
    haml :contact
end

Once we’ve done that, we’ll go to our layout file and reference our @title variable there by including an equal sign before it.

%html
  %head
    %title= @title
  %body
     = yield

OK, so let’s restart our app and visit the site in the browser. And as you can see, the different titles are included in the pages.

Routing: Named Parameters

Sinatra allows you to add named parameters in your routes. Let’s create a string manipulator app, that will manipulate a string in various ways, depending on the URL.

So lets require 'sinatra' at the top of our file. To include a parameter in our URL, we write a colon followed by the name we want to give it. In our case we’ll call it :string.

Lets create 2 routes. Firstly, one to reverse a string. So get /reverse/:string. And secondly, one to uppercase a string, get /upcase/:string. In this example, the route patterns reverse and upcase could be named anything, we’re just choosing something sensible. The same goes for the named parameter :string.

You access the named parameter through a hash named params, just like in Rails. In our case, this will be params[:string]. So now we can call .reverse for the reverse route and .upcase for the upcase route.

require 'sinatra'

get '/reverse/:string' do
  params[:string].reverse
end

get '/upcase/:string' do
  params[:string].upcase
end

Now, lets start our application. Note we didn’t require the rubygems at the top of our application. That’s because you can pass in the -rubygems argument to the ruby command line interpreter to automatically include rubygems when running your software. So when we enter ruby -rubygems app.rb in to an open console, the Sinatra app starts up.

If we visit localhost:4567/reverse/world we get the reversed string "dlrow" returned. And if we go to localhost:4567/upcase/world we get a capitalised "WORLD" returned.

Conclusion

We’ve only scratched the surface of what Sinatra has to offer, but we hope we’ve whet your appetite, and we encourage you to look over the example-rich README on sinatrarb.com/intro.

Thanks for watching! Subscribe to our RSS feed, follow us on Twitter, and please leave any questions, comments or suggestions for new screencasts in the comments below. If you like our videos, and think your friends, followers or colleagues would benefit from seeing them, please feel free share via any of the links below the video. We really appreciate your support.

See you next time!

← Latest Episodes

blog comments powered by Disqus