rails/rails — pull request #8961 by burns (2013-01-16 04:02:51+00:00)
Title: session[:session_id] should always return an id

When a new client accesses an app, `session[:session_id]` will return `nil`,
since no session cookie was sent and no session is created until an attempt
is made to _write_ to the session hash. This patch simply forces a session
to be created if `session[:session_id]` is requested and no session exists.

A google search will show there are many who wish to access this - perhaps
for logging, or associating other records (although, I agree it's better to
simply store an associated record id _in_ the session). The most prevalent
answer seems to be to use `request.session_options[:id]`. However, I believe
`session[:session_id]` is now the preferred method of obtaining this.
Note that with this patch, the former will still return `nil` if no session exists.

However, when `session[:session_id]` is requested, I believe most developers
would not expect this to return `nil`. If they wish to know whether or not
a session already exists, they should use `session.exists?`. Otherwise, I
believe they expect to get the session id for the current session - whether
or not the session is new or not.

Note that using `protect_from_forgery` will cause the authenticity token to
be written to the session (and therefore create a session if none exists),
however this is not done until templates are rendered. Since this is the
default - and this patch would only cause session creation if `session[:session_id]`
is requested - I don't see any impact on session laziness.