二日間 Wikiクッキング その4 ページの編集ができるwiki編
編集はid引数に加えて、command引数cにeditというのを与えることで呼ばれることにする。なんて安直。
ついでに新規作成もつける。次はWiki記法かな。とりあえずここでひと休憩。100行くらいになってしまった。
#!/usr/local/bin/ruby
require 'webrick'
require 'wishi.rb'
s = WEBrick::HTTPServer.new( :Port => 2000 )
class WishiServlet < WEBrick::HTTPServlet::AbstractServlet
def simple_header
"<a href='wishi'>frontpage</a> <a href='wishi?c=create'>create</a>"
end
def edit_header(id)
"<a href='wishi?id=#{id}&c=edit'>Edit</a>"
end
def view_header(id)
"<a href='wishi?id=#{id}'>View</a>"
end
def edit(res,id)
page = PageManager.get.getPage(id)
title = page.title
body = page.body
contents =<<EOS
<form action='wishi' method="post">
TITLE <input type="text" name="title" size="80" value="#{title}"/> <hr/>
<textarea cols="80" rows="24" name="body">#{body}</textarea>
<br/>
<input type="hidden" name="id" value="#{id}"/>
<input type="hidden" name="c" value="update"/>
<input type="submit"/>
</form>
EOS
setPage(res,
simple_header+view_header(id),
contents,
id.to_s)
end
def view(res,id)
setPage(res,
simple_header+edit_header(id),
PageManager.get.getHTML(id),
id.to_s)
end
def update(req,id)
title = req.query['title']
body = req.query['body']
PageManager.get.updatePage(id,title,body)
end
def do_GET(req,res)
dispatch(req,res)
end
def do_POST(req,res)
dispatch(req,res)
end
def dispatch(req,res)
command = req.query['c'] || ''
if command == 'create'
id = PageManager.get.makePage
return edit(res,id)
end
id = req.query['id']
return frontpage(req,res) if id == nil || id.to_i == 0
id = id.to_i
case command
when 'update'
update(req,id)
return view(res,id)
when 'edit'
return edit(res,id)
else
return view(res,id)
end
end
def setPage(res,header,contents,footer)
res.body = "<html>#{header}<hr/>#{contents}<hr/>#{footer}</html>"
res['Content-Type'] = "text/html"
end
def frontpage(req,res)
contents = PageManager.get.get_list.map{ |id|
"<a href='?id=#{id}'>#{PageManager.get.getPage(id).title}</a>"
}.join("<br/>")
setPage(res,simple_header,contents,req.query.inspect)
end
end
s.mount("/wishi", WishiServlet)
trap("INT"){ s.shutdown }
s.start