Sinatra Cookie handling in 0.9.4
September 23rd, 2009 adminI had an older post about cookie handling with Sinatra, and a few details are out of date. This is a current view (as of September 2009) of how cookies work in Sinatra.
First, you need to set cookies via the response object, as Sinatra no longer has a helper for it.
response.set_cookie("foo", "bar")
Second, set_cookie always takes two arguments. If you need to set advanced options, pass a hash:
# the large number is several years in the future, in seconds response.set_cookie("foo", {:value => "bar", :expiration => Time.today + 94608000}
There are a good handful of options available. One gotcha with the expires option is that it must respond to .gmtime, which the Date object does not. So you need to use Time or DateTime as far as I can tell.
set_cookie("thing", { :value => "thing2", :domain => myDomain, :path => myPath, :expires => Time.today, :secure => true, :httponly => true } )
To read the underlying code for setting cookies, it’s in the rack gem, rack-1.0.0/lib/rack/response.rb line 56.
To fetch cookies, it’s simply calling the cookie method:
cookies["foo"] # => "bar"