Who is online, really?
Posted by Eric Stewart Thu, 15 Dec 2005 16:53:00 GMT
Courtenay was pondering today how to figure out who is online in your Rails app. I’m liking his solution better thank what I thought up on this a few days back, but since he asks….
My solution was a bit quicker and dirtier. I wanted to jump in and get a list without that oh-so-tedious (wink) process of creating a new model class. So, what I did was:
Make sure I was using ActiveRecordStore for sessions.
Just as Courtenay describes, create your sessions table:
rake create_sessions_table
But remember, I was trying to avoid an actual model class. Moving on…
Create a handy controller action
This is the meat of it. In the action I want to use to list active sessions I do something like this.
@sessions = CGI::Session::ActiveRecordStore.session_class.find(:all)
@session_pages = Paginator.new self, @sessions.size, 10, @params['page']Of course, I was tring to be all fancy and show a paginated listing of active sessions.
Then..
Slap a nice view in
Put a nice view in and access your sessions data (in helper or rhtml template) like so:
session.data['user'].fullname
Technorati Tags: rails, ruby, session management
<!





Just out of curiosity, how do you handle session expiry for a case like this?
I assume you mean filtering expired sessions from your new view.
Since your expiry_time is in your data you still need something to load those session objects, which is really a separate problem from listing recently updated sessions.
Since the default session table includes
As he did, I add the following to mycreated_atandupdated_at, I can use those just as Courtenay did still not needing a model object of my own.findcall:That filters out sessions that haven’t been updated recently from my view. You still want a filter that updates some data within the session on regular user activity to update the “updated_at” periodically.
All I’ve managed to do is avoid creating a separate class, though I’m in serious danger of my code breaking if something changes in the default session table/class. That’s why I mentioned in my post that I like Courtenay’s solution better.
On the subject of cleaning out sessions, you still need a way to expire them and delete them, such as storing an expiry_time in the session data and having an action (or external script) periodically go through and delete those expired sessions.