From: Paul Brannan Date: 2007-09-04T22:20:03+09:00 Subject: Re: Resource Acquisition & Cleanup I used to use an idiom like this: class Rollback attr_reader :procs def initialize @procs = [] end def undo(&b) @procs << b end def self.rollback rb = self.new begin yield rb rescue Exception rb.procs.reverse.each do |p| p.call rescue Exception end raise end end end Rollback.rollback do |rb| rb.undo { puts "1" } rb.undo { puts "2" } rb.undo { puts "3" } raise "FOO" end # => 3 # => 2 # => 1 # => RuntimeError: FOO Looking back I think I could/should have picked a better name, but the idea is that after you allocate each resource, call rb.undo to set up a rollback procedure if an exception is raised later on. I think I posted this somewhere to ruby-talk a few years ago, but I couldn't find the post. Paul