File: ttl.rb

package info (click to toggle)
ruby-redis-store 1.10.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 312 kB
  • sloc: ruby: 1,480; makefile: 6
file content (47 lines) | stat: -rw-r--r-- 1,334 bytes parent folder | download
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
class Redis
  class Store < self
    module Ttl
      def set(key, value, options = nil)
        if ttl = expires_in(options)
          setex(key, ttl.to_i, value, :raw => true)
        else
          super(key, value, options)
        end
      end

      def setnx(key, value, options = nil)
        if ttl = expires_in(options)
          setnx_with_expire(key, value, ttl.to_i, options)
        else
          super(key, value)
        end
      end

      protected
        def setnx_with_expire(key, value, ttl, options = {})
          with_multi_or_pipelined(options) do |transaction|
            if transaction.is_a?(Redis::Store) # for redis < 4.6
              setnx(key, value, :raw => true)
              expire(key, ttl)
            else
              transaction.setnx(key, value)
              transaction.expire(key, ttl)
            end
          end
        end

      private
        def expires_in(options)
          if options
            # Rack::Session           Merb                    Rails/Sinatra
            options[:expire_after] || options[:expires_in] || options[:expire_in]
          end
        end

        def with_multi_or_pipelined(options, &block)
          return pipelined(&block) if options.key?(:cluster) || options[:avoid_multi_commands]
          multi(&block)
        end
    end
  end
end