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:

 1require 'rubygems'
 2require 'haml'
 3require 'cgi'
 4
 5# A Hash for all of the variables we want to send to HAML
 6model = {}
 7
 8# Why not get the time
 9model[:time] = Time.now
10
11cgi = CGI.new
12
13# Set up the template
14haml_engine = Haml::Engine.new(File.read('../templates/index.haml'))
15
16# Render out the HTML
17cgi.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