-
Notifications
You must be signed in to change notification settings - Fork 6
/
redis_driver.rb
70 lines (56 loc) · 1.23 KB
/
redis_driver.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
70
require "redis"
require "psych"
require "json"
class RedisDriver
include Enumerable
class << self
def from_env(key)
new(uri, key)
end
private
def uri
host = config["hostname"] || config["host"]
if config.has_key?("password")
"redis://:#{config["password"]}@#{host}:#{config["port"]}/0"
else
"redis://#{host}:#{config["port"]}/0"
end
end
def config
vcap_services = JSON.parse(ENV.fetch("VCAP_SERVICES", default_vcap_services))
(vcap_services["rediscloud"] || vcap_services["p-redis"])[0].
fetch("credentials")
end
def default_vcap_services
JSON.generate(
"rediscloud" => [
{ "credentials" => { "hostname" => "localhost",
"port" => "6379" } }
]
)
end
end
def initialize(uri, key)
@redis = Redis.new(url: uri)
@key = key
end
def <<(value)
redis.rpush(key, Psych.dump(value))
end
def clear
redis.del(key)
end
def each(&block)
elements.each do |element|
block.call(Psych.load(element))
end
end
def length
redis.llen(key)
end
private
def elements
redis.lrange(key, 0, length - 1)
end
attr_reader :redis, :key
end