Skip to content

Instantly share code, notes, and snippets.

@timyates
Created September 11, 2012 12:43
Show Gist options
  • Save timyates/3698144 to your computer and use it in GitHub Desktop.
Save timyates/3698144 to your computer and use it in GitHub Desktop.
Add an ensureClosed method to Object in Groovy
Object.metaClass.ensureClosed = { Closure c ->
try {
c( delegate )
}
finally {
[ delegate ].flatten().each {
if( it.respondsTo( 'close' ) ) {
it.close()
}
}
}
}
// Create a FileWriter, close it when finished
new FileWriter( '/tmp/d.txt' ).ensureClosed {
it.println 'd'
}
// Create 3 FileWriters, close them all when done, and return
// Closure result ('tim') to the rslt var
def rslt = [ '/tmp/a.txt', '/tmp/b.txt', '/tmp/c.txt' ].collect {
new FileWriter( it )
}.ensureClosed { a, b, c ->
a.println 'a'
b.println 'b'
c.println 'c'
'tim'
}
assert rslt == 'tim'
// This works, but does nothing
'tim'.ensureClosed {
println it
}
@cdeszaq
Copy link

cdeszaq commented Sep 19, 2012

You could extend this "ensure*" concept to just about any method you would like to ensure gets called. It's most useful for cleanup like this, but I could easily see "ensureOpen" or something similar being useful for some things as well.

I would be curious to know if the Groovy language is flexible enough to be able to have an "ensure*" method that would pick up on whatever * is and turn that into the method it tries to call.

Well done!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment