水口玄造 水口玄造 - 3 months ago 7
Ruby Question

How to set a cookie in Sinatra

I am developing a web application using Sinatra and Ruby. I need to set a cookie that is accessible from all subdomains. My original code was this:

@language = 'en-US'
cookies[:USER_LANGUAGE] = @language


This produced the desired effect (e.g. setting the cookie "USER_LANGUAGE" equal to "en-US"

However, it was not accessible from all subdomains. After looking at How to set a cookie on a separate domain in Rails and other similar questions, I have tried this:

@language = 'en-US'
cookies[:USER_LANGUAGE] = {
:value => @language,
:domain => '.example.com'
}


When I check the cookie data, it is set completely wrong. The value of the cookie is everything inside the brackets, and the domain is still only
example.com
(not
.example.com
)

Here is the value produced:

%7B%3Avalue%3D%3E%22en-US%22%2C+%3Adomain%3D%3E%22.example.com%22%7D

mwp mwp
Answer

If you want all your cookies to be accessible from all subdomains, you can set the cookie options for your application:

set :cookie_options, :domain => '.example.com'

If just need it on one cookie, you can do this (instead of using the cookies object):

response.set_cookie(:USER_LANGUAGE, :value => @language, :domain => '.example.com')