Ruby CGI with DBI

2005-11-21 23:25:00

I just got another e-mail about that old article I wrote for O'Reilly Network about using AJAX to do song search for my Webcast radio station.

Interestingly though, this e-mail wasn't asking about the AJAX stuff -- this guy wanted to know about the server-side Ruby code I mention in the article.

Ruby is fantstic for Web programming -- simple or complicated. Unfortunately everyone is so focused on the Rails hype that plain vanilla Web programming kind of takes a back seat.

For using Ruby's DBI to talk to a database -- including how to iterate through a recordset, you can check out the excellent resource at Kitebird. And LinuxJournal has a good article that talks about how to use the basic Ruby CGI module for Web programming.

Most of the CGI examples use that complicated HTML-generation stuff to craft the markup for the page. I actually tend just to build a string of content throughout the script execution and then write the whole thing out at the end -- it's way less complicated for someone like me who's comfortable working directly with markup, and managing string data myself.

I do it kind of like this:


require 'cgi'
require 'dbi'

cgi = CGI.new
content = ''

content += 'Some stuff<br/>'
content += 'Some more stuff'
content += <<DOC
This is content inside of a heredoc.<br/>
I can do linebreaks and stuff in here.

cgi.out() { content }

You can get the full rundown on the CGI module from the online version of the Pickaxe book as well.

You can get a performant Ruby CGI app by using either FastCGI or mod_ruby. The kind folks at ZTtracks have a somewhat old but nice resource on setting up Apache to serve a mod_ruby Web app.


This is the blog for Matthew Eernisse. I currently work at Yammer as a developer, working mostly with JavaScript. All opinions expressed here are my own, not my employer's.


Previous posts

All previous posts ยป

This blog is a GeddyJS application.