Module: CatchCache::Cache

Defined in:
lib/catch_cache/cache.rb

Class Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



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
# File 'lib/catch_cache/cache.rb', line 4

def included(klass)
  klass.class_eval do
    def self.catch_then_cache(redis_key, &block)
      redis = Redis.new
      val = redis.get(redis_key)

      # retrieve the cache with redis_key as its key
      cache = JSON.parse(val.blank? ? "[]" : val)

      if cache.blank?
        timeline_logs = block.call
        redis.set(redis_key, timeline_logs.to_json)
        cache = JSON.parse(redis.get(redis_key))
      end

      cache
    end

    def catch_then_cache(redis_key, &block)
      redis = Redis.new
      val = redis.get(redis_key)

      # retrieve the cache with redis_key as its key
      cache = JSON.parse(val.blank? ? "[]" : val)

      if cache.blank?
        timeline_logs = block.call
        redis.set(redis_key, timeline_logs.to_json)
        cache = JSON.parse(redis.get(redis_key))
      end

      cache
    end
  end
end