John Lam 1997 — 2026

RubyCLR and auto_dispose

In the second drop of RubyCLR, I had a broken implementation of auto_dispose, which automatically calls an object’s Dispose method for you. Fortunately, Gunter Szolderits noticed this problem, and sent me a really lovely implementation that allows for parallel assignment. That means that instead of writing this:

auto_dispose(D.new) do |dc|
  auto_dispose(AD.new) do |adc|
    adc.good_method
  end
  dc.good_method
end

you can now write this:

auto_dispose(D.new, AD.new) do |dc, adc|
  adc.good_method
  dc.good_method
end

Using the new interfaces implementation, the implementation of auto_dispose now looks like this:

def auto_dispose(*objs)
  yield(*objs) if block_given?
ensure
  objs.each do |obj|
    if obj != nil
      disposable = obj.as IDisposable
      disposable.dispose if disposable != nil
    end
  end
end

Now, is that pretty or what? And I mean both the usage and the implementation!

6 archived reader comments

G??nter Szolderits (2006-02-28)

Your implementation looks really good! I didn’t know that obj.as exists. Nice piece of code :-)

John Lam (2006-02-28)

Yes - the as method was a big step forward in working with interfaces. All of that + hopefully a first pass of generics will be in the next drop.

Dave (2006-02-28)

you don’t like the name “using”?

John Lam (2006-02-28)

I have a similar method called autoclose for classes (like XmlTextReader) that don’t implement IDisposable. I needed to have some way to distinguish the methods, so I settled on the autozzz methods.

John Lam (2006-02-28)

I have a similar method called auto_close for classes (like XmlTextReader) that don’t implement IDisposable. I needed to have some way to distinguish the methods, so I settled on the auto_zzz methods.

Dave (2006/02/28)

you don’t like the name "using"?