Module: CacheUtils::Controller

Extended by:
ActiveSupport::Concern
Defined in:
lib/cache_utils/controller.rb

Instance Method Summary collapse

Instance Method Details

#cache_bundle(*objects) ⇒ Object



5
6
7
# File 'lib/cache_utils/controller.rb', line 5

def cache_bundle(*objects)
  objects.map { |o| cache_key_for(o) }.join(':')
end

#cache_if(condition, name = {}, options = nil, &block) ⇒ Object



19
20
21
22
23
24
25
# File 'lib/cache_utils/controller.rb', line 19

def cache_if(condition, name = {}, options = nil, &block)
  if condition
    fetch_cache(name, options, &block)
  else
    yield
  end
end

#cache_key_for(object) ⇒ Object



9
10
11
12
13
14
15
16
17
# File 'lib/cache_utils/controller.rb', line 9

def cache_key_for(object)
  if object.respond_to?(:cache_key)
    object.cache_key
  elsif object.is_a?(Hash)
    serialize_hash(object)
  else
    object.to_s
  end
end

#fetch_cache(key, _options = nil) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/cache_utils/controller.rb', line 41

def fetch_cache(key, _options = nil)
  cached = $redis.get(key)
  if cached
    Appsignal.increment_counter('cache_hit', 1) if defined?(Appsignal)
    return cached
  end
  Appsignal.increment_counter('cache_miss', 1) if defined?(Appsignal)
  if block_given?
    fresh = yield
    $redis.set(key, fresh)
    fresh
  end
end

#get_cache(key) ⇒ Object



27
28
29
30
31
32
33
34
35
# File 'lib/cache_utils/controller.rb', line 27

def get_cache(key)
  cached = $redis.get(key)
  if cached
    Appsignal.increment_counter('cache_hit', 1) if defined?(Appsignal)
    return cached
  end
  Appsignal.increment_counter('cache_miss', 1) if defined?(Appsignal)
  nil
end

#render_with_cache(object, condition, name = {}, options = nil) ⇒ Object



59
60
61
62
63
# File 'lib/cache_utils/controller.rb', line 59

def render_with_cache(object, condition, name = {}, options = nil)
  render jsonapi: cache_if(condition, name, options) {
                    serialize_for_cache(object)
                  }, raw: true
end

#serialize_for_cache(object, options = {}) ⇒ Object



55
56
57
# File 'lib/cache_utils/controller.rb', line 55

def serialize_for_cache(object, options = {})
  ActiveModelSerializers::SerializableResource.new(object, options)
end

#set_cache(key, content) ⇒ Object



37
38
39
# File 'lib/cache_utils/controller.rb', line 37

def set_cache(key, content)
  $redis.set(key, content)
end