O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

14.16. Writing a CGI Script

Credit: Chetan Patil

Problem

You want to expose Ruby code through an existing web server, without having to do any special configuration.

Solution

Most web servers are set up to run CGI scripts, and it's easy to write CGI scripts in Ruby. Here's a simple CGI script that calls the Unix command ps, parses its results, and outputs the list of running processes as an HTML document.[6] Anyone with access to the web server can then look at the processes running on the system.

	#!/usr/bin/ruby
	# ps.cgi

	processes = %x{ps aux}.collect do |proc|
	  '<tr><td>' + proc.split(/\s+/, 11).join('</td><td>') + '</td></tr>'
	end

	puts 'Content-Type: text/html'
	# Output other HTTP headers here…
	puts "\n"

	title = %{Processes running on #{ENV['SERVER_NAME'] || `hostname`.strip}}
	puts <<-end
	  <HTML>
	   <HEAD><TITLE>#{title}</TITLE></HEAD>
	   <BODY>
	   <H1>#{title}</H1>
	   <TABLE>
	    #{processes.join("\n")}
	  </TABLE>
	  </BODY>
	  </HTML>
	end

	exit 0

Discussion

CGI was the first major technology to add dynamic elements to the previously static Web. A CGI resource is requested like any static HTML document, but behind the scenes the web server executes an external program (in this case, a Ruby script) instead of serving a file. The output of the program—text, HTML, or binary data—is sent as part of the HTTP response to the browser.

CGI has a very simple interface, based on environment variables and standard input and output; one that should be very familiar to writers of command-line programs. This simplicity ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required