Lazycoder

25Feb/050

new adventures in Ruby – part one

So I decided to explore writing a CGI application in Ruby on my iBook tonight. I wanted to see if I could build a simple tool in a language I didn’t know in an evening. We’ll see how this goes. I’m going to try and write a simple weblog application. It will store the results in a file located in the same directory as the CGI script. I don’t think it will allow editing of past posts,maybe. I’ll have to see. It’s not going to be fancy. It’ll datetime stamp each post and display them.

First of all, I have to get Ruby and install it. I used Fink to install whatever the latest version of Ruby is. Looks like 1.8.1-1. After that was set up, I enabled CGI in my user ~/Sites directory (I had previously enabled personal web sharing). This wasn’t very hard since I wasn’t trying to set up a hardened server. I just opened up a terminal (I use iTerm), went into /etc/httpd/users and edited my user .conf file so it looked like this.

#add in a handler. I'm using .rub for no particular reason.
#make sure that ExecCGI is listed in the Options
AddHandler cgi-script .rub

    Options Indexes MultiViews ExecCGI
    AllowOverride None
    Order allow,deny
    Allow from all

Ok, I’ve got that enabled. So now I’ll start seeing what I can do with Ruby. I start by looking at the examples here.

My first Ruby script.

#!/sw/bin/ruby
print "Content-type: text/html\r\n"
print "

Hello World

\r\n"

alright, it works. But I’m not going to print out every line of html in this program by hand. Looks like there are some CGI classes. Lets try them. The CGI classes let you write out the beginning tags and will automagically close them for you. You can nest the tags by starting a new tag within the {} of another. It works a lot like the HtmlTextWriter in ASP.NET.
Second script

#!/sw/bin/ruby
require 'cgi'
cgi = CGI.new("html3")
cgi.out{
cgi.html{
	cgi.head{"\n"+cgi.title{"This is a test"} } +
	cgi.body{"\n" +
		cgi.h1{ "Hello World" } + "\n"
		}
	}
}

Pretty easy so far, but I’m in curly bracket hell. I can also mix in Ruby code with HTML using the old aligator tags (< % %>). Yay, I’m back in 1997! Ok, so I’ve figured out how to output stuff to the browser. Now I need to dig into the OOP aspects of Ruby and start building some objects.