Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Ruby CGI programming


May 12, 2021 Ruby


Table of contents


Ruby CGI programming

Ruby is a common language, not just one for WEB development, but Ruby is most common in WEB applications and WEB tools.

With Ruby you can not only write your own SMTP server, FTP program, or Ruby Web server, but you can also use Ruby for CGI programming.

Next, let's take a moment to school Ruby's CGI editing.


Web browsing

To better understand how CGI works, we can click on a link or URL process on the web page:

  • 1, use your browser to access the URL and connect to the HTTP web server.
  • 2, the Web server receives the request information will resolve the URL, and find out whether the accessed file exists on the server, if there is the contents of the return file, otherwise the error message is returned.
  • 3. The browser receives information from the server and displays the received files or error messages.

CGI programs can be Ruby scripts, Python scripts, PERL scripts, SHELL scripts, C or C?programs, etc.


CGI architecture diagram

Ruby CGI programming


Web server support and configuration

Before you program CGI, make sure that your Web server supports CGI and that CGI handlers are configured.

Apache supports CGI configurations:

Set up the CGI directory:

ScriptAlias /cgi-bin/ /var/www/cgi-bin/

All HTTP server execution CGI programs are stored in a pre-configured directory. This directory is called the CGI directory, and by convention it is named /var/www/cgi-bin directory.

The extension of the CGI file .cgi, and Ruby can also use the .rb extension.

By default, the Linux server configuration runs in the cgi-bin directory for /var/www.

If you want to specify other directories that run CGI scripts, you can modify the httpd.conf profile as follows:

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

Add the .rb suffix to AddHandler so that we can access the Ruby script file at the end of .rb:

AddHandler cgi-script .cgi .pl .rb

Write a CGI script

The most scripted Ruby CGI code looks like this:

#!/usr/bin/ruby puts "HTTP/1.0 200 OK" puts "Content-type: text/html\n\n" puts "This is a test"

You can keep the code in the test .cgi file, the last time you went to the server and gave you enough permissions to execute it as a CGI script.

If you have an address of http://www.example.com/, you can use http://www.example.com/test.cgi to access the program with the output: "This is a test."

After the browser visits the URL, the Web server finds the test.cgi file in the site directory, then parses the script code through the Ruby parser and accesses the HTML document.


Use 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 for a script.

#!/usr/bin/ruby

require 'cgi'

cgi = CGI.new
puts cgi.header
puts "<html><body>This is a test</body></html>"

In the following code, the CGI object is created and the header information is printed.


Form processing

Using the CGI library, you can get data for form submission (or parameters in a URL) in two ways, such as URL:/cgi-bin/test.cgi? F irstName=Zara&LastName=Ali。

You can get the parameters FirstName and LastName directly using CGI.

#!/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 is used to retrieve all key values:

#!/usr/bin/ruby

require 'cgi'
cgi = CGI.new
cgi.keys         # =>  ["FirstName", "LastName"]

If the form contains more than one field with the same name, the value of the same field is saved in the array.

In the following example, you specify three identical fields in the form, name, 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 is no need to discriminate between the two methods.

Here's the relevant HTML code:

<html>
<body>
<form method="POST" action="http://www.example.com/test.cgi">
First Name :<input type="text" name="FirstName" value="" />
<br />
Last Name :<input type="text" name="LastName" value="" /> 

<input type="submit" value="Submit Data" />
</form>
</body>
</html>

Create Form forms and HTML

CGI contains a number of methods for creating HTML, and each HTML tag has a corresponding approach. Before you can use these methods, you must create a CGI object through CGI.new.

To make label nesting easier, these methods use the content as a block of code that returns the string as the content of the label. Here's what it looks like:

#!/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 escape

When you work with parameters or HTML form data in a URL, you need to escape the specified special characters, such as quotation marks ("), backslashes (/).

Ruby CGI objects provide CGI.escape and CGI.unescape methods to handle the escape of these special characters:

#!/usr/bin/ruby

require 'cgi'
puts CGI.escape(Zara Ali/A Sweet & Sour Girl")

The above code executes 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('<h1>Zara Ali/A Sweet & Sour Girl</h1>')

The above code executes as follows:

&lt;h1&gt;Zara Ali/A Sweet & Sour Girl&lt;/h1&gt;'

Methods commonly used in CGI classes

Here's how to do with the complete CGI class in Ruby

  • Ruby CGI - Methods related to the standard CGI library

Cookies and Sessions