- 2009-08-23 (日) 18:47
- Programming | Review
勉強するするといいながら、あんまり進んでいないスクリプトのお勉強。
今日は Sinatra で遊んでみた。
require 'rubygems'
require 'sinatra'
require 'kconv'
require 'uri'
helpers do
def protected!
response['WWW-Authenticate'] = %(Basic realm="Testing HTTP Auth") and \
throw(:halt, [401, "Not authorized\n"]) and \
return unless authorized?
end
def authorized?
@auth ||= Rack::Auth::Basic::Request.new(request.env)
@auth.provided?
&& @auth.basic?
&& @auth.credentials
&& @auth.credentials == ['admin', 'admin']
end
end
set :content, File.dirname(__FILE__) + '/content'
get '/post/:filename' do |n|
protected!
t = URI.decode(n).tosjis
if File.exists?("./content/#{t}.txt")
f = open("./content/#{t}.txt")
s = f.read
f.close
s
else
erb %{
<h1>#{t}.txt の作成</h1>
<form action="/post/#{t}" method='POST'>
<dl>
<dt>本文</dt>
<dd>
<textarea type='text' name='body'></textarea>
</dd>
</dl>
<input type='submit' value='作成'>
</form>
}
end
end
post '/post/:filename' do |n|
protected!
t = URI.decode(n).tosjis
f = File.open("./content/#{t}.txt",'w')
f.puts params[:body]
f.close
end
http://locathost:4567/post/タイトル名 でアクセスしたら、(タイトル名).txt を ./content に作成できる、いわば遠隔メモ帳。もしアクセスした際に(タイトル名).txt が存在していれば、それを表示する。我ながらへたくそだw
Windows 環境で作ってみたのだけど、2・3点詰まった。
まず、最近の Windows ファイルシステムは内部的にUnicode化されているけれど、実際にアクセスする際は文字コードにSJISを使う必要がある。
あと、URIから渡された文字列は、IEだとエンコードの必要があるが、Firefox では必要がないかもしれない。両者で挙動が違う…これはこまった。最悪、UAで振り分けて、それぞれにビューを用意しなくちゃあかんのか?(前掲のコードでは、Firefoxで文字化けになる)。もしかしたら、今回はビューの部分を手抜きしたのでそのせいかもしれないけれど。あとは適当にBASIC認証をかけておいた。(これはSinatraの公式サイトのコードを丸パクリ)
ruby すら初心者同然なのに sinatra ってみるという暴挙に出たのだけど、これは結構楽ちんだな。よくある一発ネタのWebサービス構築には最適かも?DBとか使い出したら、Rails の方が簡単そうだけど(それも、慣れた人なら sinatra の方がいいかもしれない)。
- Newer: 男子校におけるヒエラルキー?
- Older: VALUEDOMAIN + DiCE でダイナミックDNS

