Archive for April, 2008

Running Ruby scripts in Apache2

Wednesday, April 2nd, 2008

Create a directory in your webroot (e.g. /var/www/ruby/ on Debian/Ubuntu) to store and execute your Ruby scripts and add the following directives to a .htaccess file in that directory:

AddHandler cgi-script .rb
Options +ExecCGI

Note: these directives can (and should) be specified in the Apache sites configuration file if you have permission to edit it.

To test that files in the created directory are being properly executed, copy (or download) the following code into a file named test.rb within the directory:

#!/usr/bin/env ruby
require "cgi"
cgi = CGI.new("html4")
cgi.out{
  cgi.html{
    cgi.head{ "\n"+cgi.title{"Ruby is working!"} } +
    cgi.body{ "\n"+
      cgi.h1 { "Ruby is working!" } + "\n"+
      cgi.p { "Now it's time to get on with some real work." }
    }
  }
}

Change the permissions on your file so that it is executable (chmod 774 should work fine) and visit the page you created (e.g. http://example.com/ruby/test.rb) with a web browser.

Hopefully, you should see a successful Ruby test page.

Encoding QR Codes using Ruby

Tuesday, April 1st, 2008

I've recently been working on a project at the University of Bath (I'm a Software Developer in their e-Learning Team) that aims to increase mobile/handheld access to online resources by promoting the use of QR Codes.

Obviously, the first thing I needed was a QR Code generator and I set about creating one using rQRCode (a Ruby library for encoding QR Codes, developed by Duncan Robertson) and RMagick (a Ruby interface to the ImageMagick image processing libraries).

To output the QR Code as an image, I created a class, QRImage, that extends Magick::Image and then used the following code to output the image to a file:

# QR Code parameters
text = 'http://mattroper.co.uk/'
size = 3
level = 'h'
 
# Produce the QR Code
require 'rubygems'
require 'rqrcode'
qr = RQRCode::QRCode.new(text,  :size => size, :level => level)
 
# Create the image and double its size
require 'qr_image'
img = QRImage.new(qr).sample(2)
 
# Write image to disk
img.write('/home/matt/Desktop/qr.png') { quality = 100 }