Ruby: Simple Scripts With CGI

I’m a big fan of Ruby, and still every time I need some simple server-side functionality – you know those go there, take that sort of tasks – I have to revert to good old PHP. It’s obvious that building a full-blown Rails app is an overkill.

This morning I need another tiny little script to parse the HTML page and get some info back in JSON. And all this for a static web-site, so that it can’t be hosted locally. So what do I do? Getting back to roots…

Many web servers let you run CGI scripts, which is nothing else but an ordinary script that is executed by an interpreter of your choice and the results are thrown back as the response. Of course, it’s a bit more complicated that that, but the gist is accurate, and what’s more important is it’s hilariously easy to write.

If you happen to have a site with CGI enabled, you can try it right away. If not, well, check the hosting docs, or your web server configuration to see if there’s anything you can do. Most often, you will find the cgi-bin directory where all magic happens sitting next to public_html or www in your web site location root. Don’t forget that everything you put into cgi-bin has to be executable by the web server. It means that either you need to give it the correct ownership and the owner execution permissions or simply let everyone run it (which is dangerous sometimes, but good enough for a couple of tests).

So, here’s what you can try throwing into /cgi-bin/ruby.cgi:


puts 'Content-type: text/plain'
puts 'Test Complete'

Now when you run it by entering http://your_site/cgi-bin/ruby.cgi in the address line, you will get the nice and shiny “Test Complete” string.

Note that content type declaration and the empty line after it. Two things are important about these:

  • Both lines are mandatory
  • You can set any content type you like, not just output things in plain text. It can be JSON, XML, HTML or GIF, PNG, PDF – anything you can think of.

Now why don’t you throw a couple of gems into the mix and build something cool, fast and breathing!