From: Ara.T.Howard@... Date: 2004-10-14T00:54:34+09:00 Subject: Re: Sharing variables across methods On Thu, 14 Oct 2004, David Garamond wrote: > When writing short scripts (several pages long) I often want to share > some variables (like CGI object, DB connection object) in several > methods. I often use globals for this: > > $cgi = CGI.new('html3') > $conn = PGconn.connect(...) > > def foo > $conn.exec(...) > $cgi.out { ... } > end > > When I don't want to see all those dollar signs, I use a wrapper method: > > $_cgi = CGI.new('html3') > def cgi; $_cgi end > > def foo > cgi.out { ... } > end > > But it still looks ugly to me. Any suggestion to make it more elegant? what you are saying is that you want something that shares state and methods - this is a perfect oportunity to create a class: class CGIApp def initialize opts = {} @cgi = CGI::new 'html3' @pgconn = PGconn::connect(*opts['pgconn']) end def foo @pgconn.exec ... @cgi.out ... end end if you also need a global handle on the object created and, like in this case, there can be only one of them extent at a time, you can hang some class methods of the class to retrive the object - for instance use the multiton pattern: class CGIApp class << self attr :instance def new(*a,&b); @instance ||= super; end end end kind regards. -a -- =============================================================================== | EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov | PHONE :: 303.497.6469 | When you do something, you should burn yourself completely, like a good | bonfire, leaving no trace of yourself. --Shunryu Suzuki ===============================================================================