0

这是我一直在网上看到的如何设置 cookie 的示例。

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 相比做什么,或者是否有区别?

谢谢,

列维

4

1 回答 1

2

我相信这条线:

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

正在冲洗你的标题。

在我的 TTY 中运行代码后,

内容类型:文本/html
内容长度:0
设置 Cookie:rubyweb=CustID%3D123&Part%3DABC; 路径=

内容类型:文本/html

已发出,并且 "Content-Length: 0" (由 out{} 中的空字符串生成)可能告诉浏览器您已完成。

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; 
}
于 2009-04-12T05:05:41.440 回答