aboutsummaryrefslogtreecommitdiffstats
path: root/actionpack/lib/action_dispatch/middleware/session/mem_cache_store.rb
blob: 28e3dbd732aaca5fc459d8499cf6b857b16baa25 (plain) (blame)
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
53
54
55
56
module ActionDispatch
  module Session
    class MemCacheStore < AbstractStore
      def initialize(app, options = {})
        require 'memcache'

        # Support old :expires option
        options[:expire_after] ||= options[:expires]

        super

        @default_options = {
          :namespace => 'rack:session',
          :memcache_server => 'localhost:11211'
        }.merge(@default_options)

        @pool = options[:cache] || MemCache.new(@default_options[:memcache_server], @default_options)
        unless @pool.servers.any? { |s| s.alive? }
          raise "#{self} unable to find server during initialization."
        end
        @mutex = Mutex.new

        super
      end

      private
        def get_session(env, sid)
          sid ||= generate_sid
          begin
            session = @pool.get(sid) || {}
          rescue MemCache::MemCacheError, Errno::ECONNREFUSED
            session = {}
          end
          [sid, session]
        end

        def set_session(env, sid, session_data)
          options = env['rack.session.options']
          expiry  = options[:expire_after] || 0
          @pool.set(sid, session_data, expiry)
          sid
        rescue MemCache::MemCacheError, Errno::ECONNREFUSED
          false
        end

        def destroy(env)
          if sid = current_session_id(env)
            @pool.delete(sid)
          end
        rescue MemCache::MemCacheError, Errno::ECONNREFUSED
          false
        end

    end
  end
end