Hi! I'm Nathan Hoad


Intro to Sinatra - Make an IP Checker

In case you haven't chanced upon it already, Sinatra is a lightweight Ruby framework. It's perfect for simple one-function kinds of web applications that don't require the complexities of Rails. Getting started with Sinatra is easy and for this quick example we will be making a very simple app - one that will tell us what our IP address is.

Let's get things started by installing the Sinatra gem:

sudo gem install sinatra

Now we need a project folder that we can keep all our stuff in:

mkdir ip-checker
cd ip-checker

Then create an 'app.rb' file with this in it:

require 'rubygems'
require 'sinatra'

# This tells Sinatra to respond to the default route
get '/' do
  "Hello World"
end

The "Hello World" is there just for testing at the moment; we will do something more interesting soon. Now, make sure everything is ok so far by using Sinatra's built-in development server. Just run:

ruby app.rb

And then go to http://localhost:4567 (4567 being the default port of the server) and you will see "Hello world". Go back to Terminal and kill the server by pressing Ctrl+C.

With me so far? No? Surely you meant yes... Yes? That's better

Now we want to actually do something useful - check our IP. We will be using HAML for our templates so we will need to get it installed:

sudo gem install haml

Then we need to require it in our app (on the line after we required Sinatra before):

require 'haml'

This next line is optional; it just tells HAML to use HTML5 tags. Add this just after the require 'haml':

set :haml, { :format => :html5 }

Now we can modify our default route to add the IP checking code:

get '/' do
  # Grab the users IP
  @ip = request.env['REMOTE_ADDR'].split(',').first
  # Render our Index template
  haml :index
end

Before we can run this we need to make our Index template. Create a new folder inside our project folder called 'views'. Now in our views folder we can create our Index view. Name it 'index.haml' and put this inside of it:

!!! Strict
%html
  %head
    %title
      Your IP is
      = @ip    
    %link{:rel => "shortcut icon", :type => "image/png", :href => "/favicon.png"}/
    %link{:rel => "stylesheet", :type => "text/css", :href => "/stylesheets/application.css"}/

  %body
    %h1
      Your IP is
      %em
        = @ip

If you are unfamiliar with HAML don't worry too much - all you need to notice is the '@ip' references. They are the same as the '@ip' that we defined back in 'app.rb'.

If everything has gone to plan so far we should now have a semi-useful app. Try running it again with ruby app.rb and see for yourself.

So that wraps it up for this super simple intro to Sinatra. Now you've got no excuse not to try it out

Find out more about Sinatra at sinatrarb.com and Sinatra on GitHub.

If I just made your day a little better then thank me with a coffee or maybe a a pizza