Project

General

Profile

Feature #13923

Idiom to release resources safely, with less indentations

Added by tagomoris (Satoshi TAGOMORI) almost 3 years ago. Updated almost 3 years ago.

Status:
Feedback
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:82888]

Description

In programs which grabs and releases resources very often, we need to write so much begin-ensure clauses.

begin
  storage = getStorage()
  begin
    buffer = storage.get(buffer_id)

    # ...
  ensure
    buffer.close if buffer
  end
rescue StorageError => e
  # ...
ensure
  storage.close if storage
end

Such code makes our code fat, and difficult to understand.
I want to write such code like below:

# Class of storage and buffer should include a module (like Closeable)
# or be checked with respond_to?(:close)

begin(storage = getStorage(); buffer = storage.get(buffer_id)
  # ...
rescue StorageError => e
  # ...
end
# (buffer.close if buffer) rescue nil
# (storage.close if storage) rescue nil

Other languages also have similar features:

  • Java: try-with-resources
  • Python: with

Also available in: Atom PDF