Nov 28

Cleaning up Rails Session Records

etienne @ 8:07 pm

Similar:
  • None Found
  • In the Rails Cookbook there is an article describing how to clean up stale session records periodically, i.e. 13.14 Cleaning Up Residual Session Records. When I attempted to set this up as described in the book there was a couple of problems.

    1. I have a few additional require statements in my config/environment.rb which includes some of my custom classes which I’m serializing.

    require ‘app/models/survey_item’
    require ‘app/models/survey_group’

    The problem was that the cron job was failing as it could not find these files so I had to modify the cron job from the suggested

    */10 * * * * ruby /srv/www/htdocs/apps/<appname>/script/runner \
    script/runner -e production SessionCleanup.nuke_old_db_session

    to

    */10 * * * * cd /srv/www/htdocs/apps/<appname> && ruby script/runner \
    -e production SessionCleanup.nuke_old_db_sessions

    2. Now my cron job was running but if was deleting all my sessions, it was as if it was comparing the wrong time so the condition was always true. I use UTC time in my application and realised I had to make a slight modification to the function in the environment.rb that deletes the session records to take this into consideration, so I changed the function from:

    # Clean up session
    class SessionCleanup
      def self.nuke_old_db_sessions
        CGI::Session::ActiveRecordStore::Session.destroy_all(
          [’updated_at < ?’, 20.minutes.ago]
        )
      end
    end

    to

    # Clean up session
    class SessionCleanup
      def self.nuke_old_db_sessions
        CGI::Session::ActiveRecordStore::Session.destroy_all(
          [’updated_at < ?’, 20.minutes.ago.utc]
        )
      end
    end
     

    By adding the .utc to 20.minutes.ago fixed the problem.

     

    Tags: cron, Rails, Ruby

    Leave a Reply