brianhempel/mongo_session_store — pull request #22 by airtonsobral (2013-10-16 19:56:35+00:00)
Title: Added support for running custom code before save session

A nice feature missing is to customize the Session class, adding attributes, indexes and another stuff useful to the application.

To do this you can simply add code to the class Session inside ActionDispatch::Session::MongoidStore (or the others stores available).
But inside this class you can use almost nothing of your app, like the environment or the session data (before it's converted to binary).

A simple solution is in this pull request: Add a call to a method called "before_save_session" passing the major variables availables: "env", "sid", "session_data" and "options". This method is suposed to be implemented by the application using this gem.

Now you can do this (if you're using warden) to save the user_id in the session:

``` ruby
module ActionDispatch
module Session
class MongoidStore < MongoStoreBase
class Session

field :user_id, :type => Moped::BSON::ObjectId
index({ user_id: 1 })

def before_save_session(env, sid, session_data, options)
puts "before_save_session"
if !self.user_id && env['warden'] && env['warden'].user
self.user_id = env['warden'].user._id
end
end

end
end
end
end
```

With the user_id in the session (in database) you can do fun things like remove all sessions from a specific user.

Cheers