Your First Sinatra Apps

Sinatra is a DSL (domain-specific-language) for building websites, web services, and web apps in Ruby. A DSL is usually dedicated to solving a particular type of problem. SQL (structured query language) is another example of a DSL. SQL is used to facilitate interaction with relational database systems.

Sinatra is not a Framework like Rails. It doesn’t come with a pre-fabricated file structure or even a project folder. Sinatra is a lean language and is being used by companies like GitHub, Heroku, BBC, ThoughtBot, and Songbird.

The two main approaches to building Sinatra apps are classic and modular. In classic mode you just require Sinatra and start defining end-points. Classic applications are often single-file, standalone apps that are run directly from the command line or with a minimal rackup file. In modular mode you explicitly subclass Sinatra and build your app within that scope. You would take a modular approach if you wanted to build many small apps within a parent app. Think about mixins in Ruby, they’re just little modules(blocks of code) you can use throughout your app or you can have an entire app of just interacting mixins!

So why not use Sinatra for all of your apps and be done with it? Every technology has it’s place. Sinatra is usually reserved for smaller apps. If you want to build the next WordPress you could theoretically do it in Sinatra but using Rails would be more appropropriate. Why not just learn Rails from the outset? Same reason you probably shouldn’t try learning JavaScript as your first programming language. Learning Ruby is more practical and gives you a fundamental grasp of using a language to communicate with a machine. I’m so glad I learned Ruby before tackling other languages. Sinatra is less robust and is great warm-up for learning Rails.

So how do you install Sinatra? Easy! Type gem install sinatra anywhere in your command line. You should also install the Thin web server by typing gem install thin. Why Thin you ask? Thin is a Ruby web server that glues together 3 of the best Ruby libraries in web history:

  • the Mongrel parser, the root of Mongrel speed and security
  • Event Machine, a network I/O library with extremely high scalability, performance and stability
  • Rack, a minimal interface between webservers and Ruby frameworks

Which makes it, the most secure, stable, fast and extensible Ruby web server bundled in an easy to use gem for your own pleasure.

Let’s build our first “Hello World!” App! Jump back to your command line and make a directory for your sinatra app:

Open the folder in your text editor (sublime . ) and type the following:

Now make sure the file is saved and type ruby server.rb back in your command line. By default the application will listen on port 4567 so go ahead and open your web-browser and navigate to http://localhost:4567/ Your sinatra app should respond and you should see “Hello, world!” in the top left of your browser window. Congrats! Your first Sinatra App!

So what’s this sorcery? Sinatra separates the developer from middleware called Rack. No, nothing to do with Tyga’s hit single ‘Rack City.’ Rack provides a minimal interface between web-servers (e.g. Thin) that support DSL’s. Sinatra is going to use Rack to talk to Thin (our web-server). Essentially Sinatra speaks Italian, Rack speaks Italian and German, and Thin speaks German. We have to use Rack as our translator.

Sinatra DSL syntax is typically expressed in the form: verb ‘route’ do. We’re instructing our application to respond to HTTP GET requests to the path ‘/’; our apps response (behavior) is inside of the block. So when a server (Thin) hollers atcha app, your app responds: “Hello, world!” This block is appropriately named a method call. In Sinatra, a route is an HTTP method paired with a URL-matching pattern. Each route is associated with a block:

In Sinatra Routes are matched in the order they are defined. The first route that matches the request is invoked. This means, if you have another get ‘/’ do request beneath your Hello World request, the Hello World will be the only one triggered for this ‘/’ request.

rock-paper-scissors

Now let’s put some of what we learned to use and build a simple Rock Paper Scissors web-app! In your command line control-c out of your server connection and rename your server.rb file to game.rb (mv server.rb  game.rb). before we start processing routes we have to set up a before block with plain text responses and a hash with all viable moves:

This code will be stored in memory before our route is processed. Let’s set up our route and set a player_throw:

The most important thing to understand in this program is the params hash, the rest of the code in our block will be basic ruby. You’ll be using params in pretty much every Rails and Sinatra program you write. The params hash stores querystring data. What the heck is querystring? A very simplistic explanation is, it’s the last piece of data in any URL (Uniform Resource Locator). A more accurate definition is: A querystring is a set of characters input to a computer or Web browser and sent to a query program to recover specific information from a database. On the Internet, a querystring (also called an HTTP querystring) is part of the set of characters automatically input in the address bar of a dynamic Web site. For example, consider the following URL:

:www.bookfinder4u.com/search_author/Ernest_Hemingway.html?sort=date

The querystring in this example consists of one field or variable, technically called a key in this context (the word “sort”), followed by an equals sign (=), followed by the value for that key (the word “date”). A querystring may contain several key-value pairs. When there is more than one key-value pair, they are typically separated by ampersands (&). So params is just a Hash with key value pairs. And we use this hash to pass along information from one request(page) to another. This will make more sense as we finish building our first web game.

The only thing left to tackle that might seem unfamiliar is the ‘halt’ command. It’s pretty simple, processing will stop immediately once the halt command is called. The player_throw will essentially be fixed and placed at the end of your URL. The computer_throw is random (.sample). Yall should be able to work your way through the rest of the logic.

So that’s our basic game! Let’s test it. Jump back into your command line and type ruby game.rb to establish connection with your server. Once you’re connected open your browser and navigate to http://localhost:4567/throw/rock or http://localhost:4567/throw/scissors or http://localhost:4567/throw/paper . Notice how we (the player) is inputing the throw in our URL, and the computer (the program) is generating it’s own throw and comparing it with ours. Keep refreshing your browser and you’ll see different results. What do you think you can do to set off halt 403? Just type anything besides our three set inputs at the end of our URL.