Created
September 11, 2012 12:43
-
-
Save timyates/3698144 to your computer and use it in GitHub Desktop.
Add an ensureClosed method to Object in Groovy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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!