Disposable Code
I took a quick look at some WaitN examples this morning to see if there was anything I needed to fear when doing an example of WaitN in IronRuby. Then I saw it. IDisposable. More correctly, a using statement. What would that look like in IronRuby?
module System::IDisposable
def self.use_these(*disposers, &block)
block.call(*disposers)
disposers.each {|d| d.dispose}
end
def using(&block)
block.call(self)
self.dispose
end
end
class DisposableHero
include System::IDisposable
attr :name
def initialize(name = "Jed")
@name = name
end
def do_something_to(other)
puts "#{@name} washes a car for #{other.name}"
end
def do_something
puts "#{@name} doing something"
end
def dispose
puts "#{@name} is being disposed"
end
end
DisposableHero.new.using do |d|
d.do_something
end
System::IDisposable.use_these(DisposableHero.new("Tony"), DisposableHero.new("Ryan")) do |t, r|
t.do_something_to(r)
end
I added a using method to any IDisposable object that handles scoping. In addition, I added a multi-object disposing use_these block so I don’t have to nest my using blocks. It’s not perfect, but for five minutes of thinking, it’s not too bad.
September 18th, 2009 at 2:53 pm
I like this. It’s yet another example of how useful rub’s dynamicness is.
The one change that I’d make would be to put the calls to dispose in a rescue block… in addition to being closer in functionality to c#’s using, it makes ‘using’ return what the block returned instead of what dispose returns.
September 18th, 2009 at 7:07 pm
That’s a great idea, and more idiomatic. Thanks!
Here’s a gist with the updates