在 Ruby CGI 编程中,使用 CGI 模块可以方便地处理 Cookie。以下是一些关于 Ruby CGI Cookie 的基本用法:

设置 Cookie
require 'cgi'

cgi = CGI.new

# 设置一个名为 'user' 的 Cookie,值为 'John'
user_cookie = CGI::Cookie.new('name' => 'user', 'value' => 'John')

# 将 Cookie 添加到响应头
cgi.out('cookie' => user_cookie)

puts "Content-type: text/html\n\n"
puts "<html>"
puts "<head><title>Cookie Example</title></head>"
puts "<body>"
puts "<h1>Cookie Set</h1>"
puts "Cookie value: #{cgi.cookies['user'].value}"
puts "</body>"
puts "</html>"

获取 Cookie
require 'cgi'

cgi = CGI.new

puts "Content-type: text/html\n\n"
puts "<html>"
puts "<head><title>Cookie Example</title></head>"
puts "<body>"

# 获取名为 'user' 的 Cookie
user_cookie = cgi.cookies['user']

if user_cookie
  puts "<h1>Cookie Value</h1>"
  puts "Cookie value: #{user_cookie.value}"
else
  puts "<h1>Cookie Not Found</h1>"
end

puts "</body>"
puts "</html>"

删除 Cookie
require 'cgi'

cgi = CGI.new

# 创建一个过期时间在过去的 Cookie,达到删除效果
expired_cookie = CGI::Cookie.new('name' => 'user', 'value' => '', 'expires' => Time.at(0))

# 将过期的 Cookie 添加到响应头
cgi.out('cookie' => expired_cookie)

puts "Content-type: text/html\n\n"
puts "<html>"
puts "<head><title>Cookie Example</title></head>"
puts "<body>"
puts "<h1>Cookie Deleted</h1>"
puts "</body>"
puts "</html>"

这是一个简单的 Ruby CGI Cookie 的示例。实际中,你可能需要更加复杂的逻辑和安全性考虑,例如设置过期时间、安全标志等。如有其他问题,请随时提问。


转载请注明出处:http://www.zyzy.cn/article/detail/13447/Ruby