Last Updated: March 31, 2016
·
3.285K
· jimeh

Ruby: #wait_while

# Public: Wait while block returns false by repeatedly
# calling the block until it returns true.
#
# Useful to wait for external systems to do something.
# Like launching daemons in integration tests. Which 
# you're not actually doing right? >_<
#
# timeout        - Integer specifying how many seconds
#                  to wait for.
# retry_interval - Interval in seconds between
#                  calling block while it's
#                  returning false.
# block          - A block which returns true or false.
#                  It should only return true when
#                  there no need to wait any more.
#
# Returns false if timeout reached before block returned
# true, otherwise it returns true.
def wait_while(timeout = 2, retry_interval = 0.1, &block)
  start = Time.now
  while (result = !!block.call)
    break if (Time.now - start).to_i >= timeout
    sleep(retry_interval)
  end
  !result
end