Sha256: cfcc56438bcb51086bef4197a9cce6645370724df34073762fb229cacc15312b

Contents?: true

Size: 1.06 KB

Versions: 5

Compression:

Stored size: 1.06 KB

Contents

module WaitWatchers
  class TimeoutError < StandardError; end

  # method to wait until block passed returns truthy (false will not work) or
  # timeout (default is 2 seconds) is reached raises TiemoutError on timeout
  #
  # @returns the truthy value
  #
  # @example 
  #     
  #   @a = nil
  #
  #   th = Thread.new do
  #     sleep(1)
  #     @a = :fudge
  #   end
  #
  #   wait_until(2) { @a }.should == :fudge
  #
  def wait_until(timeout=2)
    time_to_stop = Time.now + timeout
    while true
      rval = yield
      return rval if rval
      raise TimeoutError, "timeout of #{timeout}s exceeded" if Time.now > time_to_stop
      Thread.pass
    end
  end

  # inverse of wait_until
  def wait_while(timeout=2)
    time_to_stop = Time.now + timeout
    while true
      rval = yield
      return rval unless rval
      raise TimeoutError, "timeout of #{timeout}s exceeded" if Time.now > time_to_stop
      Thread.pass
    end
  end

  def report_realtime(what)
    return yield
    t = Benchmark.realtime { yield }
    $stderr.puts "#{what}: %0.3f" % [t.to_f]
  end
end


Version data entries

5 entries across 5 versions & 2 rubygems

Version Path
zk-group-0.1.1 spec/support/wait_watchers.rb
zk-1.0.0 spec/support/wait_watchers.rb
zk-1.0.0.rc.1 spec/support/wait_watchers.rb
zk-0.9.1 spec/support/wait_watchers.rb
zk-0.9.0 spec/support/wait_watchers.rb