Skip to content
This repository
Browse code

Added expect.rb from 1.9.3p0.

  • Loading branch information...
commit 981a2efde02cb71903fbf437f11036783b015d57 1 parent 7f701a7
Brian Shirai brixen authored
0  lib/expect.rb → lib/18/expect.rb
File renamed without changes
51 lib/19/expect.rb
... ... @@ -0,0 +1,51 @@
  1 +$expect_verbose = false
  2 +
  3 +class IO
  4 + # Reads from the IO until pattern +pat+ matches or the +timeout+ is over.
  5 + # It returns an array with the read buffer, followed by the matches.
  6 + # If a block is given, the result is yielded to the block and returns nil.
  7 + #
  8 + # The optional timeout parameter defines, in seconds, the total time to wait
  9 + # for the pattern. If the timeout expires or eof is found, nil is returned
  10 + # or yielded. However, the buffer in a timeout session is kept for the next
  11 + # expect call. The default timeout is 9999999 seconds.
  12 + def expect(pat,timeout=9999999)
  13 + buf = ''
  14 + case pat
  15 + when String
  16 + e_pat = Regexp.new(Regexp.quote(pat))
  17 + when Regexp
  18 + e_pat = pat
  19 + else
  20 + raise TypeError, "unsupported pattern class: #{pattern.class}"
  21 + end
  22 + @unusedBuf ||= ''
  23 + while true
  24 + if not @unusedBuf.empty?
  25 + c = @unusedBuf.slice!(0).chr
  26 + elsif !IO.select([self],nil,nil,timeout) or eof? then
  27 + result = nil
  28 + @unusedBuf = buf
  29 + break
  30 + else
  31 + c = getc.chr
  32 + end
  33 + buf << c
  34 + if $expect_verbose
  35 + STDOUT.print c
  36 + STDOUT.flush
  37 + end
  38 + if mat=e_pat.match(buf) then
  39 + result = [buf,*mat.to_a[1..-1]]
  40 + break
  41 + end
  42 + end
  43 + if block_given? then
  44 + yield result
  45 + else
  46 + return result
  47 + end
  48 + nil
  49 + end
  50 +end
  51 +

0 comments on commit 981a2ef

Please sign in to comment.
Something went wrong with that request. Please try again.