Sha256: c07eb159bd9884036aa729a4c43c296b6235b2382ae7409b8bd0aa1bafff552d

Contents?: true

Size: 1.4 KB

Versions: 5

Compression:

Stored size: 1.4 KB

Contents

module Soaspec
  class TimeOutError < StandardError; end
  # Class to enable waiting for an expected condition to return true
  class Wait
    DEFAULT_TIMEOUT  = 5
    DEFAULT_INTERVAL = 0.2

    #
    # Wait until the given block returns a true value.
    #
    # @param [Hash] opts Options for this instance
    # @option opts [Numeric] :timeout (5) Seconds to wait before timing out.
    # @option opts [Numeric] :interval (0.2) Seconds to sleep between polls.
    # @option opts [String] :message Exception mesage if timed out.
    # @option opts [Array, Exception] :ignore Exceptions to ignore while polling (default: Error::NoSuchElementError)
    # @raise [Error::TimeOutError]
    # @return [Object] the result of the block
    #
    def self.until(opts = {})
      timeout = opts.fetch(:timeout, DEFAULT_TIMEOUT)
      ignored = Array(opts[:ignore] || NoElementAtPath)
      end_time = Time.now + timeout
      last_error = nil

      until Time.now > end_time
        begin
          result = yield
          return result if result
        rescue *ignored => last_error
          # swallowed
        end
        sleep opts.fetch(:interval, DEFAULT_INTERVAL)
      end

      msg = if opts[:message]
              opts[:message].dup
            else
              "timed out after #{timeout} seconds"
            end
      msg << " (#{last_error.message})" if last_error
      raise Soaspec::TimeOutError, msg
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
soaspec-0.2.2 lib/soaspec/wait.rb
soaspec-0.2.1 lib/soaspec/wait.rb
soaspec-0.2.0 lib/soaspec/wait.rb
soaspec-0.1.18 lib/soaspec/wait.rb
soaspec-0.1.17 lib/soaspec/wait.rb