Class: Redreloader

Inherits:
Object
  • Object
show all
Defined in:
lib/redreloader.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(redis_config) ⇒ Redreloader

Returns a new instance of Redreloader.



6
7
8
9
# File 'lib/redreloader.rb', line 6

def initialize(redis_config)
  @redis = Redis.new(redis_config)
  @redis_sub = Redis.new(redis_config)
end

Class Method Details

.calcmd5(val) ⇒ Object



20
21
22
# File 'lib/redreloader.rb', line 20

def self.calcmd5(val)
  Digest::MD5.digest val
end

Instance Method Details

#[](key) ⇒ Object



11
12
13
14
# File 'lib/redreloader.rb', line 11

def [](key)
  val = with_binary_redis { @redis.getrange(key, 16, -1) }
  Zlib::Inflate.inflate(val) if val && val != ""
end

#[]=(key, val) ⇒ Object



16
17
18
# File 'lib/redreloader.rb', line 16

def []=(key, val)
  with_binary_redis { @redis.set(key, self.class.calcmd5(val) + Zlib::Deflate.deflate(val)) }
end

#digest(key) ⇒ Object



24
25
26
27
# File 'lib/redreloader.rb', line 24

def digest(key)
  data = with_binary_redis { @redis.getrange(key, 0, 15) }
  data if data != ""
end

#process_changes(key, old_digest, &bl) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/redreloader.rb', line 29

def process_changes(key, old_digest, &bl)
  @redis_sub.subscribe("__keyspace@0__:#{key}") do |on|
    on.message do |channel, message|
      old_digest = yield_if_changed(key, old_digest, &bl)
    end

    on.subscribe do |channel, message|
      # run it here to avoid race condition of change between check and subscribe
      old_digest = yield_if_changed(key, old_digest, &bl)
    end
  end
end

#with_binary_redisObject



50
51
52
53
54
55
56
# File 'lib/redreloader.rb', line 50

def with_binary_redis
  original_encoding = Encoding.default_external
  Encoding.default_external = Encoding.find('binary')
  yield
ensure
  Encoding.default_external = original_encoding
end

#yield_if_changed(key, old_digest, &bl) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/redreloader.rb', line 42

def yield_if_changed(key, old_digest, &bl)
  if (new_digest = digest(key)) && new_digest != old_digest
    newdata = self[key]
    bl.call(newdata, new_digest) if newdata
  end
  new_digest
end