2009-04-12 9 views
0

이것은 쿠키를 설정하는 방법으로 온라인에서 계속 볼 수있는 예입니다.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와 반대되는 것 또는 차이가 있는지를 설명하기를 원할 것인지 궁금합니다.

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

밖으로 당신의 헤더를 세척 할 수 있습니다 :

덕분에,

레위

+0

은 조금 더 나는 cgi.out 무엇 cgi.header는 것의 대부분을 처리하는 것을 알아 냈다. 그래서 출력을 제어하는 ​​것이 더 간결한 방법일까요? – Levi

답변

2

나는이 줄을 믿습니다.

내 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

관련 문제