Module: CacheUtils::Controller
- Extended by:
- ActiveSupport::Concern
- Defined in:
- lib/cache_utils/controller.rb
Instance Method Summary collapse
- #cache_bundle(*objects) ⇒ Object
- #cache_if(condition, name = {}, options = nil, &block) ⇒ Object
- #cache_key_for(object) ⇒ Object
- #fetch_cache(key, _options = nil) ⇒ Object
- #get_cache(key) ⇒ Object
- #render_with_cache(object, condition, name = {}, options = nil) ⇒ Object
- #serialize_for_cache(object, options = {}) ⇒ Object
- #set_cache(key, content) ⇒ Object
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 = {}, = nil, &block) if condition fetch_cache(name, , &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, = 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 = {}, = nil) render jsonapi: cache_if(condition, name, ) { 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, = {}) ActiveModelSerializers::SerializableResource.new(object, ) 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 |