File: namespace.rb

package info (click to toggle)
ruby-redis-store 1.1.6-1%2Bdeb9u1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 284 kB
  • sloc: ruby: 909; makefile: 4
file content (95 lines) | stat: -rw-r--r-- 2,358 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
class Redis
  class Store < self
    module Namespace
      def set(key, val, options = nil)
        namespace(key) { |key| super(key, val, options) }
      end

      def setex(key, ttl, val, options = nil)
        namespace(key) { |key| super(key, ttl, val, options) }
      end

      def setnx(key, val, options = nil)
        namespace(key) { |key| super(key, val, options) }
      end

      def ttl(key, options = nil)
        namespace(key) { |key| super(key) }
      end

      def get(key, options = nil)
        namespace(key) { |key| super(key, options) }
      end

      def exists(key)
        namespace(key) { |key| super(key) }
      end

      def incrby(key, increment)
        namespace(key) { |key| super(key, increment) }
      end

      def decrby(key, increment)
        namespace(key) { |key| super(key, increment) }
      end

      def keys(pattern = "*")
        namespace(pattern) { |pattern| super(pattern).map{|key| strip_namespace(key) } }
      end

      def del(*keys)
        super *keys.map {|key| interpolate(key) } if keys.any?
      end

      def mget(*keys)
        options = keys.pop if keys.last.is_a? Hash
        if keys.any?
          # Serialization gets extended before Namespace does, so we need to pass options further
          if singleton_class.ancestors.include? Serialization
            super *keys.map {|key| interpolate(key) }, options
          else
            super *keys.map {|key| interpolate(key) }
          end
        end
      end
      
      def expire(key, ttl)
         namespace(key) { |key| super(key, ttl) }
      end
      
      def ttl(key)
         namespace(key) { |key| super(key) }
      end

      def to_s
        "#{super} with namespace #{namespace_str}"
      end

      def flushdb
        del *keys
      end

      private
        def namespace(key)
          yield interpolate(key)
        end

        def namespace_str
          @namespace.is_a?(Proc) ? @namespace.call : @namespace
        end

        def interpolate(key)
          key.match(namespace_regexp) ? key : "#{namespace_str}:#{key}"
        end

        def strip_namespace(key)
          key.gsub namespace_regexp, ""
        end

        def namespace_regexp
          @namespace_regexps ||= {}
          @namespace_regexps[namespace_str] ||= %r{^#{namespace_str}\:}
        end
    end
  end
end