Beginners Guide to CGI Programming in Ruby

pradeep's Avatar author of Beginners Guide to CGI Programming in Ruby
This is an article on Beginners Guide to CGI Programming in Ruby in Ruby on Rails.
Rated 4.00 By 1 users
CGI or Common Gateway Interface was created to server content over HTTP web servers using external scripting languages like Perl, Python, Ruby, or compiled binaries of C,C++, etc. Apache, the most popular web server and also others can be easily configured to run CGI scripts.

In this article we'll be looking at configuring Apache to run CGI scripts and writing simple CGI scripts in Ruby.

Configuring Apache

In the demo example I'll be using a directory rb-bin you may change this to whatever you like, cgi-bin is very popular and generally pre-configured. Do not forget to make all your scripts in the directory executable.

Add the following to Apache's config file, and then restart Apache.

ScriptAlias /rb-bin/

<Directory "/var/www/rb-bin">
   AllowOverride None
   Options ExecCGI
   Order allow,deny
   Allow from all

Basics of CGI Scripts

Unlike PHP, with Ruby you'll need to send your own headers. Headers and content of a HTTP response is separated by 2 newlines. Let's see how to send headers, let's write our first Ruby CGI script.

Code: Ruby

print "Content-Type: text/html\n\n"
print "<h2>Hello World!</h2>"

Handling Form Data

For handling forms we'll need a Ruby library cgi, fortunately it comes bundled with Ruby. Here's how to read form values.

Code: Ruby

require 'cgi'

cgi =

name = cgi['Name']

puts cgi.header("type" => "text/html", "cache_control" => "no-cache, no-store")

puts "<h2>Hello #{name}</h2>"

In the above example we get the name & print it out.

Using Cookies

Cookies are accessed and created using the cgi library, so it's pretty simple. Let's try it with some code.

Code: Ruby

require 'cgi'

cgi =

## setting cookies
cookie1 ='name' => 'name','value' => 'Pradeep','expires' => + 3600)
cookie2 ='name' => 'city','value' => 'Kolkata','expires' => + 3600)

print cgi.header("cookie" => [cookie1,cookie2])

Reading cookies:
Code: Ruby

require 'cgi'

cgi =

print cgi.header()

name = cgi.cookies['name']

print "Name is #{name}"

Now you can get started with writing CGI scripts in Ruby. Enjoy.
coderzone, shabbir likes this