>>>>> "Martin" == Martin Maciaszek <fastjack / camelot.germanistik.fu-berlin.de> writes:

    Martin> I'm writing objects that maintain a connection to a
    Martin> database and all methods and accessors actually work on
    Martin> the database. Now I would like my objects to close the
    Martin> database connection on destruction. Since ruby uses
    Martin> garbage collection there is no explicit destructor. Are
    Martin> there any hooks that could be used for this?

You might want to take a look at the Ruby DBI design.  For one
example, Ruby/DBI provides two ways of preparing SQL statements ...

    (1) stmt = db.prepare(sql)
    (2) db.prepare(sql) { |stmt|  use_stmt_here }

(1) is the traditional way of handling prepared statements.  It
returns a statement object that you must remember to call 'finish' on
by hand.

(2) will execute the provided block by passing the prepared statement
object to the block as an argument.  When the block is done executing,
the prepare method will automatically call finish for you.  In fact,
the finish call is in an ensure clause so that finish is always
called, even in the presence of exceptions.  That's easy to forget
with (1).

I've started using method (2) in all my DBI related work.  It solves
the "don't forget to shutdown" question without making assumptions on
when GC is run and memory reclaimed.

    Martin> A second destructor-related problem arises when I tell my
    Martin> object to delete it's data from the database. The object
    Martin> is no longer useful and I would like my object to destroy
    Martin> itself. ("This object will self-destruct in 10 seconds")

I would recommend using a general form of (2) above to handle any
non-memory resource allocation.  That leaves only memory resources
that the object needs to deal with and GC works fine with that.  Just
make sure any references to your object are clobbered.

-- 
-- Jim Weirich     jweirich / one.net    http://w3.one.net/~jweirich
---------------------------------------------------------------------
"Beware of bugs in the above code; I have only proved it correct, 
not tried it." -- Donald Knuth (in a memo to Peter van Emde Boas)