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.