SSブログ

Rubyでカレンダー3(とりあえず完成編) [プログラミング]

先に示したように、HTML用の変換Rubyスクリプトを提示しますです。


#!/usr/bin/ruby
# HTMLにしちゃうと消えたりする文字を変換

puts "<pre>"
file = File.open ARGV[0]
file.each{|line|
  line.gsub!(/&/,"&amp;")
  line.gsub!(/</,"&lt;")
  line.gsub!(/>/,"&gt;")
  line.gsub!(/"/,"&quot;")
  puts line
}
puts "</pre>"



バグもあるでしょうが、とりあえず使えるようになったので、習作なので良しとしましょう。そのうち、エディタのようにキーワードとか文字列とか色分けされると見やすくていいかもね。CSSを完全無視ですが、まぁいいや。


たぶんまともに動くソースを下に。今年中ぐらいは実際のカレンダーで確認したので大丈夫っぽい。なにか間違ってたら教えてください。


#!/usr/bin/ruby
# 簡易カレンダー ver.2

require "date"
require 'cgi'

# 曜日
def printWeek
  print <<EOS;
    <tr>
    <th>日</th>
    <th>月</th>
    <th>火</th>
    <th>水</th>
    <th>木</th>
    <th>金</th>
    <th>土</th>
    </tr>
EOS
end


# 日付
def printDays(t)
  
  writeday = 1  # 書く日付
  
  # 月の一日のオブジェクト
  firstday_obj = t - (t.day - 1)        # 月の一日を得る
  firstday = firstday_obj.cwday         # 曜日を得る

  # 月の日数(28-31)。
  lastday_obj = (firstday_obj >> 1) -1  # 翌月の一日の前日、で最終日
  lastday_num = lastday_obj.day         # 最後の日付を得る
  
  (0..5).each do |week|
    puts "<tr>"
    # 一週目
    if week == 0 then
      if firstday != 7 then
        firstday.times {
          puts "<td>" + "&nbsp;" + "</td>"    # 空白をパディング
        }
      end
      # 一週目の日付
      (1..(7 - firstday)).each do |d|
        writeday = d
        puts "<td>" + writeday.to_s + "</td>"
        writeday += 1
      end
      
    # 二行目以降
    else
      7.times do
        #月の最終日だったら終わる
        break if writeday > lastday_num
        #日付書き込み
        print "<td>" + writeday.to_s + "</td>"
        writeday += 1
      end
    end
    #月の最終日だったら終わる
    break if writeday > lastday_num
    puts "</tr>"
  end

end


# カレンダーの書き込み

cgi = CGI.new
print cgi.header("text/html")

t = Date.today
10.times {|n|
  print "<table><caption>"
  print (t>>n).to_s
  print "</caption>"

  printWeek
  printDays t >> n
  puts "<hr/>"
}



デバッグ方法を考えなあかんなぁ。
 tail -f /var/log/apache2/error.log
で、エラーコードが見えるけど、正直分かりづらいのはASPと同じ。デバッガとかないのかな。printfデバッグならぬputsデバッグするしかないのか。あ、Rubyにもprintfってあるんだ…。printDaysが思ったよりも汚くなったので、どうにかしたいけどたぶん放置。


タグ:Ruby
nice!(0)  コメント(0) 
共通テーマ:パソコン・インターネット

nice! 0

コメント 0

コメントを書く

お名前:[必須]
URL:
コメント:
画像認証:
下の画像に表示されている文字を入力してください。