forked from danlucraft/retwis-rb
-
Notifications
You must be signed in to change notification settings - Fork 2
/
store.rb
70 lines (59 loc) · 1.38 KB
/
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# A storage abstraction over memcached-client API.
#
require 'memcache'
class Store < MemCache
def to_s
"Store to #{self.servers}"
end
def exists?(key)
self.get(key) != nil
end
def incr(key)
n = super(key)
return n if n
self.add(key, '0', 0, true)
self.incr(key)
end
def list_range(key, from, to)
list = self.get(key, true) # Ex: nil or "+1+2+3".
return [] unless list
(list.split('+').drop(1) || []).slice(from, to - from + 1)
end
def push(key, value, prefix="+")
# Lists are '+' delimited.
if self.prepend(key, "#{prefix}#{value}").match("NOT_STORED")
self.add(key, '', 0, true)
self.push(key, value)
end
end
def set_members_hash(key)
s = self.get(key, true) # Ex: nil or "+1+2-1"
return {} unless s
acts = s.split(/[^\+-]/) # Ex: ["+", "+", "-"]
vals = s.split(/[\+-]/).drop(1) # Ex: ["1", "2", "1"]
m = {}
i = acts.length - 1
while i >= 0
val = vals[i]
if acts[i] == '+'
m[val] = true
else
m.delete(val)
end
i = i - 1
end
m
end
def set_members(key)
self.set_members_hash(key).keys()
end
def set_add(key, value)
self.push(key, value, prefix="+")
end
def set_delete(key, value)
self.push(key, value, prefix="-")
end
def set_member?(key, value)
self.set_members_hash(key)[value]
end
end