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:
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:
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):
This next line is optional; it just tells HAML to use HTML5 tags. Add this just after the
Now we can modify our default route to add the IP checking code:
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:
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.