David,

> When writing short scripts (several pages long) I often
> want to share some variables (like CGI object, DB
> connection object) in several methods.
> ...
> Any suggestion to make it more elegant? I often use
> globals for this:
>
> $cgi = CGI.new('html3')
> $conn = PGconn.connect(...)
>
> def foo
>   $conn.exec(...)
>   $cgi.out { ... }
> end

    Well, you could just use constants:

MyCGI = CGI.new('html3')
MyConn = PGconn.connect(...)

def foo
  MyCGI.exec(...)
  MyCGI.out { ... }
end

    A better, but much more verbose way would be to instantiate a
singleton class for your globals:

require 'singleton'

class Globals
  include Singleton
  attr_accessor(:cgi,:conn)
end

Globals.instance.cgi = CGI.new('html3')
Globals.instance.conn = PGconn.connect(...)

def foo
  Globals.instance.conn.exec(...)
  Globals.instance.cgi.out { ... }
end

    There are other ways to do this too, but this should get you
started.

    I hope this helps.

    - Warren Brown