Module: Common::CacheAside

Overview

Cache Aside pattern for caching responses in redis. Requires the class mixing it in to be a Common::RedisStore and the cached response class to implement a #cache? method.

Instance Method Summary collapse

Instance Method Details

#cache(key, response) ⇒ Object

create method



49
50
51
52
# File 'lib/common/models/concerns/cache_aside.rb', line 49

def cache(key, response)
  set_attributes(key, response)
  save
end

#cached?(key:) ⇒ Boolean

get method

Returns:

  • (Boolean)


28
29
30
# File 'lib/common/models/concerns/cache_aside.rb', line 28

def cached?(key:)
  self.class.find(key) ? true : false
end

#do_cached_with(key:) ⇒ Object

get or create method

Raises:

  • (NoMethodError)


33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/common/models/concerns/cache_aside.rb', line 33

def do_cached_with(key:)
  cached = self.class.find(key)
  if cached
    set_attributes(key, cached.response)
    return cached.response
  end

  response = yield
  raise NoMethodError, 'The response class being cached must implement #cache?' unless response.respond_to?(:cache?)

  # if not cached, add to cache
  cache(key, response) if response.cache?
  response
end