unkou.rb

毎日、徒歩で通勤しているので、本来であれば、電車が遅れようが全く関係ないのですが・・
通勤ルートに踏切があり、電車が遅れると踏切が開かずの扉になるため、出かける前は気にしています。(遅れている場合違うルートを使う)
そんなわけで、いちいちホームページを見るのが面倒なので、JR西日本が提供しているサイトから、そのページが変化したらメールするスクリプトを書いてみました。
ruby初心者なので、詳しい人がいたら、採点してくれるとうれしいです。

#!/usr/local/bin/ruby

$mail_to = "携帯メールアドレス"
$mail_from = "送付元メールアドレス"

def test_mail(subject, body)
  require 'net/smtp'
  require 'kconv'

Net::SMTP.start( 'smtpサーバ名', 25 ) {|smtp|
    smtp.send_mail <<EndOfMail, "#{$mail_from}", "#{$mail_to}"
From: to <#{$mail_from}>
To: phone <#{$mail_to}>
Subject: #{Kconv.tojis(subject)}
Date: #{Time.now.rfc2822}
MIME-Version: 1.0
Content-Type: text/plain; charset="iso-2022-jp"
Content-Transfer-Encoding: 7bit
X-Mailer: unkou #{$UNKOU_VERSION}

#{Kconv.tojis(body)}
EndOfMail
}

end


# main

require "open-uri"

fp = open("http://trafficinfo.westjr.co.jp/list.html")

count = 1
detail_array = Array.new

while line = fp.gets
  if line =~ /\"(.*detail.*)\"/
    $test = $1
    detail_array.unshift($1)
  end
end

$traffic_url =  "http://trafficinfo.westjr.co.jp"

if (0 == detail_array.size)
 exit()
end

# 遅延情報分テキストを作成
# 一旦読み込んで改行を除いたファイルを作成
detail_array.each{ |n|
  url = $traffic_url + "/" + n
  fp = open(url)
  fp_w = open("temp.txt", "w")
    # 改行の削除
    while line = fp.gets
      temp = line.chomp
      fp_w.print temp
    end

  fp.close
  fp_w.close

  fp_tmp = open("./temp.txt")
  while line = fp_tmp.gets
    if line =~ /.*"#eef6ee">(.*?)<\/td>/
      text_unkou = $1

      dir = Dir.open(".")
      dir.each{ |name|
        next if name == "."
        next if name == ".."

        fp_name = open(name)
          $line_tmp = fp_name.gets
        fp_name.close
        if ($line_tmp == text_unkou)
          exit();
        end
      }

    # text_unkouを保存
    text_unkou_fp = open("./" + Time.now.to_i.to_s + ".txt", "w")
      text_unkou_fp.print text_unkou
    text_unkou_fp.close

    end
  end
  fp_tmp.close

  # すべての保存ファイルが一致しなかったので、text_unkouをメール
  test_mail("JR西日本運行情報", text_unkou)
}