ShiftEleven

Don't Forget About Little Old CGI

Rails is great and all, but sometimes it can be just a little too much and you just need to set up a few pages, not the next big app. Fear not, there is still tool in the ruby tool box at your disposal: the CGI library. CGI is fast and lean and still can be used will all of your favorite friends, like HAML

Since you're using CGI, you don't have to worry about setting up FCGI, or Mongrel. You can use mod_ruby if you're using Apache or cgi with Lighttpd.

So now that servers are out of the way, time for some code.

I mentioned that you don't have to give up HAML. So for that, I propose this little directory structure.

mysite/
   |- templates/
   `- public/

Hopefully you guessed that templates contains your HAML templates and public is the webroot for your site. Now in your public directory, create an index.rb file, and perhaps it could somewhat look like:

require 'rubygems'
require 'haml'
require 'cgi'

# A Hash for all of the variables we want to send to HAML
model = {}

# Why not get the time
model[:time] = Time.now

cgi = CGI.new

# Set up the template
haml_engine = Haml::Engine.new(File.read('../templates/index.haml'))

# Render out the HTML
cgi.out { haml_engine.render(Object.new, model) }

And there's the tedious code. There are some interesting pieces to notice. For one, when calling cgi.out, that sends out the proper headers out to the browser (very important). Also, this could probably be wrapped up into a nice function to reduce the strain of repeating one's self.

Comments

comments powered by Disqus