Article
article.rb
実際の掲示板で記事のクラスを扱うときには参照にくらべて作成はかなり少ないはずです。
なので、newをファイルからの読み込みメソッドにし、
新規投稿用にArticle.postを作成します。
また、記事の要素としては「ID」、「名前」、「タイトル」、「コメント」に加え「投稿日時」、「IPアドレス」を追加します。
さらに、記事のエラーを特定するために記事エラークラス(ArticleError)を追加しましょう。
class Article
#参照メソッド
attr_reader :id, :title, :name, :comment, :ip
$; = $, = "\t"
@@id = []
def initialize( line )
id, title, name, comment, date, ip = line.chomp.split()
@id = id.to_i
raise ArticleError, "読み込み時に記事IDの不正がありました。" if @@id.include?( @id )
@@id.push( @id )
@title = title.to_s
@name = name.to_s
@comment = comment.to_s
@date = date.to_i
@ip = ip.to_s
end
def Article.post( title, name, comment, ip )
#記事IDの取得
id = @@id.first.to_i + 1
#タイトルをチェック
title = title.to_s
title.gsub!( $;, " " )
title.gsub!( /[\r\n]/, "" )
title = CGI.escapeHTML( title.strip )
title = "無題" if title == ""
#名前をチェック
name = name.to_s
name.gsub!( $;, " " )
name.gsub!( /[\r\n]/, "" )
name = CGI.escapeHTML( name.chomp.strip )
name = "名無し" if name == ""
#コメントをチェック
comment = comment.to_s
comment.gsub!( $;, " " )
comment.gsub!( /[\r\n]+$/, "" )
comment = CGI.escapeHTML( comment.strip )
comment.gsub!( /\r\n/, "<br />" )
comment.gsub!( /[\r\n]/, "<br />" )
raise ArticleError, "コメントがありません。" if comment == ""
#日時の取得
date = Time.now.to_i
#記事インスタンスの作成
Article.new( [ id.to_s, title, name, comment, date.to_s, ip ].join() )
end
def to_s
[ @id, @title, @name, @comment, @date, @ip ].join()
end
def date
Time.at( @date ).strftime("%y/%m/%d(%a) %H:%M:%S")
end
end
class ArticleError < StandardError
end
投稿日時は内部では数値型でもっておくと便利です。
$;はString#splitの区切り文字、$,はArray#joinの区切り文字で、どちらもタブを指定しておきます。