Read data in an ActiveRecord-based Rails session

January 12, 2010 by alex

Here’s a simple method you can use in a console to determine the contents of an existing Rails session. All you need is the session id.

def read_session( sess_id )
  result = ActiveRecord::Base.connection.select_all( "SELECT * FROM sessions WHERE session_id = '#{sess_id}'" )
  Marshal.restore( Base64.decode64( result[ 0 ][ 'data' ] ) ) if result[ 0 ]
end

The return value will be a Hash , or nil if no session is found for that id.

Note this doesn’t do any input-escaping, so it’s open to SQL injection. Don’t expose this code to users. (That’s a good idea for lots of reasons, given what it does.)

Suppose you want to just watch a particular session in your console…

def report_session( sess_id )
  i = 0
  while true
    puts "#{i} : #{read_session( sess_id ).inspect}"
    i += 1
    sleep 1
  end
end
$ script/console
Loading development environment (Rails 2.2.2)
>> report_session 'a3fbc5de20723a242b54a73cad4221bb'
0 : {"flash"=>{}}
1 : {"flash"=>{}}
2 : {"flash"=>{}}
3 : {"flash"=>{}}
...

It’ll keep updating with session data until you kill it with Control-c.

☙ ☙ ☙