Skip to content

Instantly share code, notes, and snippets.

@javidjamae
Last active March 31, 2016 18:42
Show Gist options
  • Save javidjamae/2ac3374cb73e61048fe8168a538aefd0 to your computer and use it in GitHub Desktop.
Save javidjamae/2ac3374cb73e61048fe8168a538aefd0 to your computer and use it in GitHub Desktop.
Ruby: #wait_while
# Original source - https://coderwall.com/p/bkrg8a/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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment