EGOPOLY

Topics include: programming, Apple, Unix, gadgets, large-scale web sites and other nerdy stuff.

My first Ruby CGI

2005-08-10 10:58:08

This is a little script that could be written in Perl, or shell. But I wrote it in Ruby. If you put it on a web server, in a directory with a bunch of jpg files, it zips them up and returns them. I use it to pull down a bunch of photos from my web site to whatever photo editing software I happen to be using.

#! /usr/bin/ruby
require "cgi"

cgi = CGI.new

url = cgi.script_name
relativepath = ""

if url =~ %r{(.*)/photozip.cgi$}
  relativepath = $1
  if relativepath =~ /\.\./
    cgi.out() { "sorry" }
  end
end

basedir = '/someplace/on/server'
localpath = basedir + relativepath 

d = Dir.new(localpath)
hasjpeg = false;
d.each do |file|
  if file =~ /jpg$/
    hasjpeg = true
    break
  end
end

if hasjpeg
  if File.file?(localpath + "/allphotos.zip")
    cgi.out("status" => "302",
            "location" => "#{relativepath}/allphotos.zip")
    { "redirect" }
  else
    Dir.chdir(localpath)
    status = `/usr/local/java/bin/jar cf allphotos.zip *.jpg`
    cgi.out("status" => "302",
            "location" => "#{relativepath}/allphotos.zip")
    { "redirect" }
  end
else
    cgi.out() { "sorry, no jpegs here." }
end