- Read Tutorial
- Watch Guide Video
Most likely you're going to be using a web framework to get your Ruby application on the Internet. In this guide we are going to talk about a framework called Sinatra. This will be an introduction to the framework with the goal being to give you an idea of what this framework is all about and how you can use it to get your Ruby programs on the web.
Sinatra is a framework built in Ruby, so its flexible, fast and lightweight. Most importantly, it lets you run Ruby code on the web without the need for a lot of Sinatra-specific code.
Let's dive in by creating a couple of files called app.rb
and config.ru
.
Open the config.ru
file, and add this code:
require './app'
This code allows the config.ru
to pull in the code from the app.rb
file.
Next, let's insert another line of code:
run HiSinatra
For this code HiSinatra
is calling a Ruby class that we'll be creating.
Before going into the code for our app.rb
file, check if you have Sinatra installed in your system. Otherwise, type:
gem install sinatra
Yes, that's right, Sinatra is simply a RubyGem, therefore you need it on your system before you can use it.
Now, go to the app.rb
file and include sinatra
in it.
require 'sinatra'
Next, we are going to create the HiSinatra
class:
class HiSinatra < Sinatra::Base get '/' do "Hey Sinatra!" end end
In this code, we are creating a class called HiSinatra
which inherits from the Sinatra::Base
class. In this class we are defining what we want shown on the homepage of the application.
To run our program we can start the server with the command rackup
in your terminal.
Next, open your browser and go to the localhost
address that was shown in the terminal (it will most likely be http://localhost:9292). It should say Hey Sinatra!
, just like this:
If you type any other URL on your browser for a page we haven't defined, such as localhost:9292/about
, it will throw an error, like this:
Now let's see how to work with parameters. Say, we want to get the age of your user, we can update the app.rb
file to look like this:
get '/:age' do "Hi, I'm #{params[:age]} years old." end
If you restart the server, go to the browser and type localhost:9292/33
, your message will be:
So that's how easy it is to get up and running with Sinatra.