Sharing variables across methods

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

Warren Brown wrote:

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

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

Sigh. Now why didn't I think of that? My mind is so used to thinking that constants can only be used for simple things like 'Foo = 3'.

Thanks!

    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')

[snip]

Nah... that is _so_ much typing and not significantly better than $cgi :slight_smile:

···

--
dave