whoisjake (owner)

Revisions

gist: 229546 Download_button fork
public
Public Clone URL: git://gist.github.com/229546.git
Embed All Files: show embed
redis_cache_store.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
require 'rack/utils'
require 'action_controller/session/abstract_store'
require 'action_controller/flash'
 
module ActionController
  module Session
    class RedisCacheStore < AbstractStore
      def initialize(app, options = {})
        require 'redis'
 
        # Support old :expires option
        options[:expire_after] ||= options[:expires]
 
        super
 
        @mutex = Mutex.new
 
        @default_options = {
          :namespace => 'rack:session',
          :host => 'localhost',
          :port => 6379
        }.merge(@default_options)
 
        @cache = options[:cache] || Redis.new(@default_options)
        
        @mutex = Mutex.new
 
        super
      end
 
      private
        def get_session(env, sid)
          sid ||= generate_sid
          begin
            session = Marshal.load(@cache[sid]) || {}
          rescue Exception, Errno::ECONNREFUSED
            session = {}
          end
          [sid, session]
        end
 
        def set_session(env, sid, session_data)
          options = env['rack.session.options']
          expiry = options[:expire_after] || 0
          @cache.set(sid, Marshal.dump(session_data), expiry)
          return true
        rescue Exception, Errno::ECONNREFUSED
          return false
        end
    end
  end
end