一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

ruby cookie用法

时间:2022-06-25 02:15:04 编辑:袖梨 来源:一聚教程网

在ruby中cookie与其它编程语言一样,有expires,domain,path,secure,name这些参考,下面先看个简单cookie实例。

cookie和session保存的都是字符串,其它类型的数据类型会强制转换成字符串的形式,所以,如果想要要在cookie或session保存对象数据,必须先将其转化成比特流形式,访问的时候再将其转换成对象的形式,这样才能在cookie或session中传递对象数据
#!/usr/bin/ruby

require "cgi"
cgi = CGI.new("html4")
cookie = CGI::Cookie.new('name' => 'mycookie',
                         'value' => 'Zara Ali',
                         'expires' => Time.now + 3600)
cgi.out('cookie' => cookie) do
   cgi.head + cgi.body { "Cookie stored" }
end


给予cookie赋值方法


class HelloController < ApplicationController
      def set_cookie
            cookies[:my_name] = "AAAA"
            redirect_to :action => "show_cookie"
      end
      def show_cookie
            my_name = cookies[:my_name]
            render(:text => "Hello #{my_name}!")
      end
end

输出所有cookie

#!/usr/bin/ruby

require "cgi"
cgi = CGI.new("html4")
cookie = cgi.cookies['mycookie']
cgi.out('cookie' => cookie) do
   cgi.head + cgi.body { "Flavor: " + cookie[0] }
end

Attribute Returned Value
name Cookie name
value An array of cookie values
path The cookie's path
domain The domain
expires The expiration time (as a Time object)
secure True if secure cookie

热门栏目