Disabling session when user is not logged in

I would like to avoid creating sessions for users who are not logged
in. To that end, I have added the following to my
ApplicationController:

session :off, :if => Proc.new { |req| req.session[:user_id].nil? }

Based on my understanding, if the Proc returns true (e.g.
session[:user_id] is null), a session will not be created. This does
not seem to be working though as a session is always created in the
DB. Any thoughts?

Thanks,
Josh

On 28 Feb 2008, at 03:56, Josh wrote:

I would like to avoid creating sessions for users who are not logged
in. To that end, I have added the following to my
ApplicationController:

session :off, :if => Proc.new { |req| req.session[:user_id].nil? }

I think the problem here is that you are accessing the request
session, which in turn causes a session to be created.
You need a way to say “give me the session if it exists, but if it
doesn’t exist don’t bother”. A cursory glance at the source
(cgi_process.rb is the interesting file suggests that there is no api
for this and you’ll just have to look for the presence of an @session
instance variable in the request object.

Fred

Thanks Fred, that did seem to be part of the problem.

Now, the trick is initializing the session when I need it in my
SessionController#new action. Any thoughts? Can I just initialize a
new CgiSession here?

Updated code:

session :off, :if => Proc.new { |req| !session_exists?(req) }

private
class << self
def session_exists?(request)
request.instance_variable_defined?(:@session)
end
end