Ruby CGI Programming
Ruby is a general-purpose language, not just a language for web development, but Ruby is most commonly used in web applications and web tools.
With Ruby you can not only write your own SMTP server, FTP program, or Ruby web server, but also do CGI programming with Ruby.
Next, let's take some time to learn Ruby CGI programming.
Web browsing
To better understand how CGI works, we can follow the flow of clicking a link or URL on a web page:
- 1. Use your browser to access a URL and connect to the HTTP web server.
- 2. After receiving the request information, the Web server parses the URL and checks whether the requested file exists on the server. If it exists, the file content is returned; otherwise, an error message is returned.
- 3. The browser receives the information from the server and displays the received file or the error message.
A CGI program can be a Ruby script, Python script, PERL script, SHELL script, C or C++ program, etc.
CGI architecture diagram

Web server support and configuration
Before you start CGI programming, make sure your web server supports CGI and has a CGI handler configured.
Apache CGI support configuration:
Set up the CGI directory:
ScriptAlias /cgi-bin/ /var/www/cgi-bin/
All HTTP servers store CGI programs in a preconfigured directory. This directory is called the CGI directory and, by convention, is named /var/www/cgi-bin.
CGI files have the extension .cgi; Ruby can also use the .rb extension.
By default, the cgi-bin directory on Linux servers is configured under /var/www.
If you want to specify another directory for running CGI scripts, modify the httpd.conf configuration file as shown below:
AllowOverride None
Options +ExecCGI
Order allow,deny
Allow from all
Add the .rb suffix in AddHandler so that we can access Ruby script files ending in .rb:
AddHandler cgi-script .cgi .pl .rb
Writing CGI scripts
The most basic Ruby CGI code is as follows:
#!/usr/bin/ruby
puts "Content-type: text/html\n\n"
puts "This is a test"
You can save this code to a test.cgi file, upload it to the server, and give it sufficient permissions to execute as a CGI script.
If your site's address is http://www.example.com/, you can access this program via http://www.example.com/test.cgi, and the output is: "This is a test.".
After the browser accesses this URL, the web server finds the test.cgi file in the site directory, then uses the Ruby interpreter to parse the script code and access the HTML document.
Using cgi.rb
Ruby can call the CGI library to write more complex CGI scripts.
The following code calls the CGI library to create a CGI script.
#!/usr/bin/ruby
require 'cgi'
cgi = CGI.new
puts cgi.header
puts "This is a test"
In the following code, a CGI object is created and the header information is printed.
Form handling
Using the CGI library, you can retrieve form-submitted (or URL parameter) data in two ways, for example the URL: /cgi-bin/test.cgi?FirstName=Zara&LastName=Ali.
You can use CGI#[] to directly get the parameters FirstName and LastName:
#!/usr/bin/ruby
require 'cgi'
cgi = CGI.new
cgi['FirstName'] # => ["Zara"]
cgi['LastName'] # => ["Ali"]
Another way to get form data:
#!/usr/bin/ruby
require 'cgi'
cgi = CGI.new
h = cgi.params # => {"FirstName"=>["Zara"],"LastName"=>["Ali"]}
h['FirstName'] # => ["Zara"]
h['LastName'] # => ["Ali"]
The following code retrieves all key-value pairs:
#!/usr/bin/ruby
require 'cgi'
cgi = CGI.new
cgi.keys # => ["FirstName", "LastName"]
If a form contains multiple fields with the same name, the values of that field are stored in an array.
In the following example, three fields named "name" are specified in the form, with values "Zara", "Huma", and "Nuha":
#!/usr/bin/ruby
require 'cgi'
cgi = CGI.new
cgi['name'] # => "Zara"
cgi.params['name'] # => ["Zara", "Huma", "Nuha"]
cgi.keys # => ["name"]
cgi.params # => {"name"=>["Zara", "Huma", "Nuha"]}
**Note:** Ruby automatically determines the GET and POST methods, so there's no need to treat the two methods differently.
The following is the related HML code:
Creating forms and HTML
CGI includes many methods for creating HTML, and each HTML tag has a corresponding method. Before using these methods, you must create a CGI object with CGI.new.
To make tag nesting simpler, these methods take the content as a block, and the block returns a string as the tag's content. As shown below:
#!/usr/bin/ruby
require "cgi"
cgi = CGI.new("html4")
cgi.out{
cgi.html{
cgi.head{ "\n"+cgi.title{"This Is a Test"} } +
cgi.body{ "\n"+
cgi.form{"\n"+
cgi.hr +
cgi.h1 { "A Form: " } + "\n"+
cgi.textarea("get_text") +"\n"+
cgi.br +
cgi.submit
}
}
}
}
String escaping
When working with parameters in URLs or HTML form data, you need to escape certain special characters, such as quotation marks (") and backslashes (/).
The Ruby CGI object provides the CGI.escape and CGI.unescape methods to handle escaping these special characters:
#!/usr/bin/ruby
require 'cgi'
puts CGI.escape(Zara Ali/A Sweet & Sour Girl")
The result of executing the above code is as follows:
#!/usr/bin/ruby
require 'cgi'
puts CGI.escape(Zara Ali/A Sweet & Sour Girl")
Another set of examples:
#!/usr/bin/ruby
require 'cgi'
puts CGI.escapeHTML('Zara Ali/A Sweet & Sour Girl
')
The result of executing the above code is as follows:
Zara Ali/A Sweet & Sour Girl
'
Commonly used methods in the CGI class
The following are the complete methods of the CGI class in Ruby
- Ruby CGI - Methods related to the standard CGI library
Cookies and Sessions
- Ruby CGI Cookies - How to handle CGI cookies.
- Ruby CGI Sessions - How to handle CGI sessions.