Search code examples
rubydesign-patternsaccessorrescue

Proper way to write an 'If it doesn't work, fix it and try again' function in Ruby


I have an accessor object which is unavoidably intermittent. Sometimes when it tries an action, its internals crash and need to be restarted before the action is reattempted.

It's easy enough to write a function like:

def might_break
    try_something_that_might_break
rescue
    fix_it
    might_break
end

With a counter to avoid infinite breakage, of course.

But I'd like to keep things DRY, and every one of my accessors methods need pretty much the same care.

I thought about making a function safely which takes a block, but then I'm not sure how I could have it return to the parent function.

Thanks in advance!


Solution

  • Do you mean something like this?

    def safely num, &block
      count = 0
      begin
        block.call
      rescue
        count += 1
        retry if count < num
      end
    end
    

    Call it with safely(5) {your_broken_method}