Mac OS X, Ruby, CGI without Rails
In the midst of my Rails based Web development I was tasked with the creation of a simple, one page Web form. I knew it would be a snap to write given my background in PHP and the broad support for PHP in OS X but I decided to “teach myself” how I could do the same thing in Ruby without the crutch of Rails.
The first step was to create the Web form with static HTML which took about 15 minutes, start to finish. I configured the form action to point to my Ruby script that would simply echo “Thanks!”.
Clicking the “Submit” button on my form produced the “Opening form_handler.rb” window (Windows readers your mileage may vary from this point forward) meaning that Apache did not know what to do with files with “.rb” extensions. A quick visit to /etc/httpd/httpd.conf to add the following line beneath the other AddHandler options did the trick.
AddHandler cgi-script .rb
After restarting Apache, and clicking the “Submit” button again I was greeted with a 500 error. A peek at /var/log/httpd/error_log revealed the following:
Options ExecCGI is off in this directory: /Users/sjobs/Sites/cgi-bin/form_handler.rb
That’s easy enough to fix. Placing a .htaccess file containing the following line resolved that issue:
Options ExecCGI
Finally, with no special modification to Apache included out-of-the-box with OS X except those changes noted above my Ruby CGI script was performing as expected. Total time invested: 30 minutes. Not bad. The basic script, which just chunks out the form values and some other stuff appears below. An excellent reference to Ruby’s CGI library is, of course, located in RDoc.
#!/usr/bin/env ruby
require 'cgi'
cgi = CGI.new("html4")
params = cgi.params
cgi.out() do
cgi.html() do
cgi.head{ cgi.title{"TITLE"} } +
cgi.body() do
cgi.pre() do
CGI::escapeHTML(
"params: " + cgi.params.inspect + "\n" +
"cookies: " + cgi.cookies.inspect + "\n" +
ENV.collect() do |key, value|
key + " --> " + value + "\n"
end.join("")
)
end
end
end
end
