2009-04-12 9 views
0

これは、Cookieの設定方法としてオンラインで見続ける例です。RubyでCGIクッキーはどのように動作しますか?

require "cgi" 
cookie = CGI::Cookie.new("rubyweb", "CustID=123", "Part=ABC"); 
cgi = CGI.new("html3") 
cgi.out("cookie" => [cookie]){ 
    cgi.html{ 
    "\nHTML content here" 
    } 
} 

このようにして、クッキーを設定して空白のページを表示します。

#!/usr/local/bin/ruby 

require 'cgi' 
load 'inc_game.cgi' 
cgi = CGI.new 

cookie = CGI::Cookie.new("rubyweb", "CustID=123", "Part=ABC"); 
cgi.out("cookie" => [cookie]){""}  

#see if game submit buttons pressed 
doIt = cgi['play'] 
puts "Content-type: text/html\n\n" 

play = Game.new 

#welcome 
if doIt == '' 
puts play.displayGreeting 
end 

#choose weapon 
play.playGame 

if doIt == 'Play' 
    move = cgi['weapon'] 
    human = play.humanMove(move) 
    computer = play.ComputerMove 
    print human 
    print computer 
    result = play.results(human,computer) 
    play.displayResults(result) 
end 

私の最初の質問は間違っていますか?第二に、誰かが.headerとは対照的に.outが何をしているのか、あるいは違いがあるのか​​を説明したいと思っているのでしょうか?

おかげで、私はこの行信じる

レヴィ

+0

もう少し読んでから、私はcgi.outは何cgi.headerが希望の多くを扱うことが分かりました。それでは、出力を制御するより簡潔な方法ですか? – Levi

答えて

2

cgi.out("cookie" => [cookie]){""} 

があなたのヘッダを洗い流すです。

私のTTYで裸のコードを実行する際に

 
Content-Type: text/html 
Content-Length: 0 
Set-Cookie: rubyweb=CustID%3D123&Part%3DABC; path= 

Content-type: text/html 

が放出され、「コンテンツ長:0」(アウト{}で空の文字列によって生成された)は、おそらくあなたがしているブラウザを語っています完了しました。

cookie = CGI::Cookie.new("rubyweb", "CustID=123", "Part=ABC"); 
cgi.header("cookie" => [cookie] , type => 'text/html') 

#normal printing here 

は、ヘッダーを送信することが好ましいであろう。

「処理する」を選択すると「出力について考える」モデルが役立つかもしれません。

require 'cgi' 
load 'inc_game.cgi' 

cgi = CGI.new 
cookie = CGI::Cookie.new("rubyweb", "CustID=123", "Part=ABC"); 

output = ""; 

#see if game submit buttons pressed 
doIt = cgi['play'] 

play = Game.new 

#welcome 
if doIt == '' 
    output << play.displayGreeting 
end 

#choose weapon 
play.playGame 

if doIt == 'Play' 
    move = cgi['weapon'] 
    human = play.humanMove(move) 
    computer = play.ComputerMove 
    output << human 
    output << computer 
    result = play.results(human,computer) 
    output << play.displayResults(result) 
end 



cgi.out("cookie" => [cookie] , type=>"text/html"){ 
    output; 
} 
+0

ヘッダーを送信すると内部サーバーエラーが発生しましたが、これは私には最適なオプションです。最後に出力を送信すると内部サーバーエラーが発生します。これは、本体にテキストを印刷しているため、印刷コンテンツが最後まで設定されていないためです。 – Levi

+0

少なくとも設計エラーと考えてください。その実際には良い考えではありません(一般的に)ランダムなコードで深く印刷文を持っている –

+0

私は心に留めておきます。あなたの最初の提案にヘッダーが内部サーバーエラーを投げる理由について何か考えていますか?何かが印刷される前に私はそれを送っています。 – Levi

関連する問題