Question

We are building a plugin for Rails to be used within iframe Facebook applications, and at one point we need to check if Rail's session id cookie as been set or not.

By default, this cookie is named _myprojectname_session, what we need to find out is the actual name of the cookie itself. So if it's not set, we can do some redirects to make sure the cookies are set.

How do we access the damn name of the cookie from anywhere? Or at least from within a controller?

Was it helpful?

Solution 2

I found the solution. In Rails 2.3.2 at least the session key in set in config/initializers/session_store.rb like this:

ActionController::Base.session = {
  :key         => '_myapp_session',
  :secret      => '[...]'
}

And you can read the value like this:

ActionController::Base.session_options[:key]

From Base.session to Base.session_options automagically, doesn't make much sense, and it caused me a big headache... lol

OTHER TIPS

Rails.application.config.session_options[:key]

To access the name of the session cookie from within the view or the controller, you can say:

request.session_options[:session_key]

and then to access the raw value of that cookie, being an empty array if it's not set, you use:

request.cookies[ request.session_options[:session_key] ]

The cookie name ( aka session_key ) is set in your config/environment.rb file.

  config.action_controller.session = {     
    :session_key => '_project_session',
    :secret      => 'long-secret-key'
  }

In my experience, if there is an underscore in the key, IE SOMETIMES does not set the cookies. In other words, use 'projectsession' instead of '_project_session'.

I think that the session key is stored in a variable called ENV_SESSION_KEY

Note also this bug which affects tests around session_options in some versions of Rails 2.x: https://rails.lighthouseapp.com/projects/8994/tickets/2303-testrequest-doesnt-initialize-session_options

In Rails 3/4 I'm using this:

request.env["rack.request.cookie_hash"]

This is a hash that contains all the cookies for current user including the one for session. The hash has as a key the name of the cookie, and as a value the value of the cookie

I couldn't work out how to do this in rails 3 :-(

Eventually I ended up putting this in config/initializers/session_store.rb

SESSION_KEY = '_myapp_session'
MyApp::Application.config.session_store :cookie_store, :key => SESSION_KEY

and then accessing this where needed, eg in a view...

<%= ::ENV_SESSION_KEY %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top