occasionally useful ruby, ubuntu, etc

23Jan/1020

A brief introduction to Ruby, Sinatra, and Haml

Ruby and Sinatra make it ludicrously easy to make a webapp, but getting started, as with any new language or framework, can be daunting. By the end of this part, you'll have a simple template that talks back to you!

I'm not going to go over how to install Ruby here (it's probably been done numerous times around the web), but here's a quick checklist:
1) Install Ruby (http://www.ruby-lang.org/en/downloads/)
2) If running Ruby 1.8.6 or 1.8.7 (check with ruby -v), install Rubygems. For more info on Rubygems, check out http://docs.rubygems.org/read/book/1 . Ruby 1.9 and above come with Rubygems built in.
3) Install the Sinatra and Haml rubygems (see http://docs.rubygems.org/read/chapter/2#page5, but the command on Linux is sudo gem install sinatra haml to install both at the same time)

As a sanity check when you're done, run "irb" (interactive Ruby), and type each of the following commands (in order). None of them should return errors.

  1. require 'rubygems'
  2. require 'sinatra'
  3. require 'haml'

Okay, now on with the good stuff.

First Steps

Create a project directory, like first_app or something. Create a file with the .rb extension, like hello.rb. Open it up in your favorite (simple?) text editor (notepad++, gedit, TextMate).

Write the following:

Let's take a step by step to figure out exactly what's going on in this file. (list numbers correspond to line numbers)

  1. "require" simply loads up a library. If it's already been loaded once, "require" will check to make sure it already loaded it and then do nothing. "require"ing rubygems loads up that library into memory so we can load other gems, like...sinatra. (Like Perl, Ruby has a number of "magic globals". The load path, where require looks, is an array in $:). Also, notice single-line comments are denoted by #. Ruby doesn't really have multiline comments amazingly, but there is a hacky substitute...
  2. Now that we have rubygems loaded, we can load sinatra! Rubygems works by modifying that $: variable I mentioned above. By loading the sinatra gem, the libraries full capabilities are now ready -- and most importantly, new methods are available in the main scope.
  3. Ah, 'get' is our first method call, which we get after loading sinatra. We're passing in one argument to it, "/hello", as well as a block. Blocks have some tricky aspects to them, but think of them as simply a way of passing a chunk of code around (see closure and Pragmatic Programmers for more info). Note that calling methods without the (optional) parentheses is generally considered against best practice, except in very simple cases, like this one.
  4. As you may have guessed, this is a string. But what is it doing? The last line of any block or method is implicitly the return value. When sinatra asks this block "what's your value", the block will hand up whatever's on the last line. Of course, you can (and sometimes have to) be more explicit by prefixing your return value with the return keyword, like Java.

If you're confused about what method calls generally look like, here's a little snippet I prepared.

Okay, let's run this thing. In your terminal, run `ruby hello.rb`. The terminal will tell you where to point your browser: http://localhost:4567/. Go there -- you should see "Hello, world!"

Okay, the basics are out of the way. Let's get to the cookbook-style programs. (be sure to note the filename, in the corner of the gist)

Render a haml template and pass data to it

Render a layout

Layouts minimize redundant code across multiple views.

Adding javascript, css, images

Plop those files into a /public subdirectory and you should be able to reference them like /my_css.css in your views. See here: Sinatra Intro.

Posting a form and using that data

Preserving session information, like logins

The Sinatra FAQ is pretty good about this one: http://www.sinatrarb.com/faq.html#sessions

I'm cutting this off a bit short, but hopefully this is enough to get you started.

EDIT: cont'd.

Basic HTML/HAML stuff

A basic "sign in" application with link bar

See this little app I made at github. Click the Download Source button on that page, and/or browse around online.

Comments (20) Trackbacks (2)
  1. Thanks for this! Im a php coder that has never used a framework. Im trying to learn (quickly) the concepts of HAML and SASS within an MVC

  2. Occasionally Useful? I beg to differ, dude. This article is the best comprehensive intro to this subject so far. And I have seen and read tons of those.

    Kudos.

    • Thanks! This is one of my more popular posts :) I might consider renaming the blog…my posts are a fair bit more practical that I was originally going for :P

  3. very useful. The problem with sinatra and haml is that there are few good examples. This is one of the best. Thanks a lot. It is however slightly unreadyable because of the inline gists. Maybe you keep them local or change the default width of your posts.

  4. Very nice, short and sweet enough for even the most lazy and stressed of programmers to fire up a web framework they’ve never used before.

    Thanks for putting this intro together :)

    (BTW I have far less than 1280 horizontal resolution, because I never browse full-screen – I find it more comfortable to read thinner columns, even if it means scrolling down more)

  5. Nice intro, thanks.

    For multi-line comments I use:

    =begin

    stuff I want
    to comment out

    =end

    Can’t remember where I picked that up, but I think it was Dave Flannigan’s The Ruby Programming Language, and I don’t think it was presented as a hacky substitute.

    • Eh, true, I just don’t like them because you have to start and end them on their own line, in the first column. I rarely use them, but it’s fair to mention them so others can.

  6. Your examples are very useful, succinct. Definitely checking your blog on a regular basis.

  7. HAML is just beautiful. Wish it was more widely supported by IDEs.

    • Yeah…though you can get syntax highlighting for haml for gedit, and redcar comes with it by default. It’s not non-existent, but not nearly as widespread as one might want.

  8. Thanks a lot.

    You have made the start so easy.

    Keep Writing

  9. What about a CRUD app example using Datamapper and PostgreSQL?

  10. It sounds all well and good, but when I include the form, I click submit and nothing happens. I am using ruby 1.9.2, Sinatra 1.3.2, haml 3.1.7; am I missing something basic?

    • Got it!!! A buddy gave me a hint, spacing is critical in HAML! I was using a VM and copying over a lot of code by hand. Since my HAML spacing was off the form did not submit. Black magic…

      • Awesome :) Yeah, spacing is certainly critical in HAML. So after experimenting a little, I discovered that if you have a submit button that isn’t in a form, clicking on it does nothing. not even redirecting to the current page (like a submit button in a form tag with no attributes would do). So I suspect that’s what happened here. You might have better luck copy-pasting if you hit the “view raw” link in the corner of the gists, or you can clone the gist straight into your VM by clicking on the filename link and then “Clone this gist” in the left hand side, like so: “git clone https://gist.github.com/284715.git“. You may need to sudo apt-get install git-core if you’re on Ubuntu/Linux Mint/Debian and don’t have git installed yet.

        Happy Sinatra-ing!


Leave a comment