From: matz@... (Yukihiro Matsumoto) Date: 1997-09-18T11:52:57+09:00 Subject: [ruby-list:4393] Re: BranchTable class まつもと ゆきひろです In message "[ruby-list:4382] BranchTable class" on 97/09/18, Yasunari Momoi writes: | |ももちゃん@アルモニコスです. | |必要に迫られて,BranchTable という (汚い (^^;)) クラスを書いて |みました.もっとうまい方法があったら教えて下さい. そうそう,コンテキストの問題がある場合には文字列でなく,イテ レータを渡すのはどうでしょう.以前に私が書いたクラスを紹介し ましょう. このクラスは最初にオブジェクトを生成しておいて,パターンをon というメソッドで追加していきます. class Expecter def initialize(timeout=nil, dynamic=nil) @timeout=timeout @action= {} @dynamic=dynamic end def on(pattern, action=lambda) @action[pattern] = action end def wait(on) keys = @action.keys while TRUE fds = select([on], nil, nil, @timeout) unless fds if @action['TIMEOUT'] @action['TIMEOUT'].call end return end break if fds.size == 0 or fds[0].size == 0 line = on.gets break unless line print line for key in keys if line =~ key @action[key].call(line) end end keys = @action.keys if @dynamic end if @action['EOF'] @action['EOF'].call end end def expect(on) fds = select([on], nil, nil, @timeout) unless fds if @action['TIMEOUT'] @action['TIMEOUT'].call end return end return if fds.size == 0 or fds[0].size == 0 line = on.gets unless line if @action['EOF'] @action['EOF'].call end return end print line for key in @action.keys if line =~ key @action[key].call(line) end end end end $connect = FALSE $num = 0 def dial $num += 1 system "#{$ppp} #{$args}&" end def redial printf "retry %d\n", $num i = 90 loop do printf "\e[10Dwait .. %02d", i STDOUT.flush sleep 0.999 i-=1 break if i < 0 end print "\e[10D" dial end expect = Expecter.new expect.on(/remote IP address/) do $connect = TRUE print "connection established\n" system '/usr/lib/sendmail -q' system 'inc' system 'ppp-off' end expect.on(/Exit/) do exit if $connect redial end f = open("|tail -0 -f /var/adm/messages") dial expect.wait(f)