Class: Primer::Cache::Redis

Inherits:
Primer::Cache show all
Defined in:
lib/primer/cache/redis.rb

Constant Summary collapse

REDIS_CONFIG =
{:thread_safe => true}

Instance Attribute Summary

Attributes inherited from Primer::Cache

#routes, #throttle

Instance Method Summary collapse

Methods inherited from Primer::Cache

#compute, #primer_identifier, #regenerate

Methods included from Watcher

call_log, included, log, loggers, on_disable, on_enable, #primer_identifier, reset!, watching

Methods included from Enabler

#disable!, #enable!, #enabled?

Constructor Details

#initialize(config = {}) ⇒ Redis

Returns a new instance of Redis.


9
10
11
12
# File 'lib/primer/cache/redis.rb', line 9

def initialize(config = {})
  config = REDIS_CONFIG.merge(config)
  @redis = ::Redis.new(config)
end

Instance Method Details

#clearObject


14
15
16
# File 'lib/primer/cache/redis.rb', line 14

def clear
  @redis.flushdb
end

#get(cache_key) ⇒ Object


25
26
27
28
29
# File 'lib/primer/cache/redis.rb', line 25

def get(cache_key)
  validate_key(cache_key)
  string = @redis.get(cache_key)
  string ? Primer.deserialize(string) : nil
end

#has_key?(cache_key) ⇒ Boolean

Returns:

  • (Boolean)

31
32
33
# File 'lib/primer/cache/redis.rb', line 31

def has_key?(cache_key)
  @redis.exists(cache_key)
end

#invalidate(cache_key) ⇒ Object


35
36
37
38
39
40
41
42
43
# File 'lib/primer/cache/redis.rb', line 35

def invalidate(cache_key)
  @redis.del(cache_key)
  
  return unless has_key?('deps' + cache_key)
  @redis.smembers('deps' + cache_key).each do |attribute|
    @redis.srem(attribute, cache_key)
  end
  @redis.del('deps' + cache_key)
end

#keys_for_attribute(attribute) ⇒ Object


53
54
55
56
# File 'lib/primer/cache/redis.rb', line 53

def keys_for_attribute(attribute)
  serial = attribute.join('/')
  has_key?(serial) ? @redis.smembers(serial) : []
end

#put(cache_key, value) ⇒ Object


18
19
20
21
22
23
# File 'lib/primer/cache/redis.rb', line 18

def put(cache_key, value)
  validate_key(cache_key)
  @redis.set(cache_key, Primer.serialize(value))
  publish_change(cache_key)
  RealTime.publish(cache_key, value)
end

#relate(cache_key, attributes) ⇒ Object


45
46
47
48
49
50
51
# File 'lib/primer/cache/redis.rb', line 45

def relate(cache_key, attributes)
  attributes.each do |attribute|
    serial = attribute.join('/')
    @redis.sadd('deps' + cache_key, serial)
    @redis.sadd(serial, cache_key)
  end
end

#timeout(cache_key, &block) ⇒ Object


58
59
60
61
62
63
64
65
# File 'lib/primer/cache/redis.rb', line 58

def timeout(cache_key, &block)
  return if has_key?('timeouts' + cache_key)
  @redis.set('timeouts' + cache_key, 'true')
  add_timeout(cache_key, @throttle) do
    block.call
    @redis.del('timeouts' + cache_key)
  end
end