This is the old RCRchive. It's available only for reading and reference. To submit RCRs for Ruby 1.9/2.0, and to participate in discussions about them, please visit the new RCRchive.
ruby picture

RCR 286: Multiple Ensure Blocks

Submitted by Graham Jenkins (Mon Dec 06 15:12:53 UTC 2004)

Abstract

Simplify resource handling by allowing multiple adjacent ensure blocks, eliminating the need for more verbose code such as nested begin...ensure...end blocks.

Problem

Top level handlers frequently require multiple resources to be cleaned up reliably. Sometimes the number of resources required is variable (for example: cleanup database resources if the supplied block has used the database; persist changes to the session object if the supplied block has used the session).

In order to make sure that all resources get cleaned up reliably, even if an exception is raised within the ensure block, we have to write additional code inside the ensure blocks that distracts from the ostensible purpose of the code.

Proposal

Change the language to allow

   begin
      ...
   ensure
       cleanup_x
   ensure
       cleanup_y
   end

which would be equivalent to

   begin
      ...
   ensure
      begin
         cleanup_x
      ensure
         cleanup_y
      end
   end

Analysis

We are allowed multiple rescue blocks to handle different types of exception. Why not multiple ensure blocks to clean up different types of resource? This change is such a natural extension of the existing exception syntax that when I first learned Ruby I expected it to be allowed already!

Implementation

N/A
ruby picture
Comments Current voting
Strongly opposed0
Opposed1
Neutral0
In favor11
Strongly advocate2
ruby picture
ruby picture

Powered by Ruby on Rails.