Gotcha when setting expires on cookies in Merb
I’ve just finished implementing ‘remember me’ functionality in a Merb app I’m working on and I came across a gotcha when setting cookies that I thought I’d post up for anyone coming across the same thing.
You can set a cookie with and expiry date in Merb using something like:
cookies.set_cookie(:foo, 'true', :secure => true, :expires => 3.days.from_now)I was setting a cookie using the value of a DateTime property on my model, something like this:
cookies.set_cookie(:auth_token, session.user.remember_token, :expires => session.user.remember_token_expires_at)Unfortunately the above code didn’t work. I eventually found out that it was down to the DateTime property on the model that I was using for the :expires option. The #set_cookie method expects :expires to be supplied with a Time object, not a DateTime object. If it isn’t given a Time object then it will not convert the value to the correct format required for a cookie. Thus you end up with a cookie that will expire at the end of the browser session instead.