Ruby CGI’s

Today will see how to use Ruby(yes, Ruby) to make our CGI tools. As you already know, CGI’s are traditional written in Perl, but if we check some Ruby’s history we can find next statement:

Ruby takes best of several worlds: Perl, Python and SmallTalk

So if we have best of Perl I think we have powerful CGI’s.

First of all we need to know that just a few free hosting services provide Ruby as an allowed scripting language, but we can always get cheap hosting(I got mine into 1 USD per month). Besides you can use your own webserver.

Every script that you write into an interpreted language begins with a line like this:

#!/usr/bin/env ruby

which says: hey! run my amazing code with Ruby(this specific case).
Now you can start write your pages in a similar way what you do into PHP, except you have to require an specific library to make the work less painful: cgi(hard to figure out, isn’t?).

#!/usr/bin/env ruby
require 'cgi'
cgi = CGI.new

Last line of code it’s just used to create a new object of class CGI.

Now, as HTTP protocol requires, our script must send the headers to web browser, if we need a custom headers must read some RFC’s and that boring stuff, instead just tell Ruby to send “standard” headers doing:

puts cgi.header

By the way, if we need to print some to the webpage just do like if you print something into terminal, I mean puts, print, printf and a lot of functions which Ruby provides.

At this point your code looks like:

#!/usr/bin/env ruby
require 'cgi'
cgi = CGI.new
puts cgi.header

Now let’s try something more interesting, assume that we got some parameters from a webform, let’s say we asked to user… mmmh, name and email, classic fields in a webform.

Nice, isn’t?. But now you can think… Yep, params it’s a Ruby hash(like an associative array in PHP), why are we processing it first like a hash and then like an array?. Well, the answer comes really faster and hits you hard…

What happened if the parameter values are several to the same parameter name?. Well, Ruby can manage that stuff, that’s why Ruby stores an array as a value of a hash. So if someone passes several names like Sheldon, Raj, Leonard and Howard we can access pretty easy:

Some of you can ask how Ruby figures out if the request was made by POST method or GET method, well, at this point Ruby takes every request type as the same. But if you wanna look which type of request the client did you can check it like this:

case ENV['REQUEST_METHOD']
when "GET"
#Do something with GET
when "POST"
#Do POST stuff
end