2009-04-12 82 views
0

這是我在網上看到的關於如何設置cookie的例子。CGI cookie如何在Ruby中工作?

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

我試過這樣做,它設置了cookie,然後出現一個空白頁。

#!/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 

所以我的問題首先是,我錯過了什麼/做錯了什麼?其次,我想知道是否有人想解釋.out做的和.header相反,還是有區別?

感謝,

列維

+0

從閱讀中我發現cgi.out可以處理cgi.header的大部分功能。所以這只是一個更簡潔的方式來控制輸出? – Levi 2009-04-12 04:10:51

回答

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 2009-04-12 16:38:49