I am looking for a style or idiom that I can apply to a resource
management problem. I have a number of resources (objects) that I need
to release if any exception is thrown. While ensure-blocks or block
parameters work well for few resources, they get cumbersome when you
have many resources, or when the number of resources is not known.
If an exception is thrown in the main processing loop, i still need to
release the resources. If an exception is thrown during construction,
i need to release the resources already succesfully created. If an
exception is thrown while releasing a resource during exception
handling, i still need to release the remaining resources.
Is there a way to do this, especially when ‘n’ is unknown?
Looking back I think I could/should have picked a better name, but the
idea is that after you allocate each resource, call rb.undo to set up a
rollback procedure if an exception is raised later on.
I think I posted this somewhere to ruby-talk a few years ago, but I
couldn’t find the post.
If an exception is thrown in the main processing loop, i still need to
release the resources. If an exception is thrown during construction,
i need to release the resources already succesfully created. If an
exception is thrown while releasing a resource during exception
handling, i still need to release the remaining resources.
Is there a way to do this, especially when ‘n’ is unknown?
This is pretty simply and should satisfy your requirements:
def your_method(n)
res = []
begin
n.times {|i| res << Resource.new(i)}
loop do
# main work
end
ensure
res.each {|r| r.release rescue nil}
end
end
Kind regards
robert
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.