Sinatra Cookie handling in 0.9.4
I 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"
September 25th, 2009 at 10:25 am
You mean “response” in the first two snippets…
October 22nd, 2009 at 2:26 am
I think the Sinatra doc should be updated on changing `set_cookie` to `request.set_cookie`
October 22nd, 2009 at 3:09 am
Hi, Chris. There’s a typo: `request.set_cookie` should be `response.set_cookie`
March 14th, 2010 at 8:02 pm
I’m testing with Cucumber a Sinatra app that sets a cookie. How do I check that the cookie has been set?
I tried this:
get “http://localhost:4567/logon/fake”
@session_id = rack_mock_session.cookie_jar[‘alc_session_id’]
@session_id.should_not be_nil
but it fails.
Here’s a dump of the cookie-jar:
#<Rack::Test::CookieJar:0xb9e08ec @default_host="example.org", @cookies=[#”/”, “domain”=>”localhost”}>]>
I think it has something to do with the path, but the ‘[]’ method selects all the cookies that match a nil path. I’m guessing that I have to set the domain and path somewhere in the test setup, but I can’t figure out where.
By the way, cookies work fine in the real (non-test) app! I just can’t get them to work in Rack/Test. Here’s the code in case you want to take a look: http://github.com/lsiden/alc.datasource
I’ll make it temporarily public.
May 2nd, 2010 at 10:03 pm
Regarding testing, I had some issues with setting a value in the session and then testing it was set correctly. I did some digging and ended up faking the session. There’s an example on my posterous page:
http://blog.verastreet.com
May 19th, 2010 at 9:53 am
I think the Sinatra doc should be updated on changing `set_cookie` to `request.set_cookie`
May 2nd, 2013 at 4:19 pm
Hi Dear, are you actually visiting this website
regularly, if so then you will without doubt get good
experience.