module ProstoCache
This library provides a simple way to cache model and to access this cache in some canonical way. Any changes to the model’s objects will automatically result in cache reload. Cache reload in other ruby processes of same app will be triggered as well, but with some delay (currently up to 60 seconds). If the delay in cache reloading is not an option, well, this simple library will not work for you, and you will have to use something fancier, like Memcached.
Usage:
-
Add
ProstoCache
mixin to your model class YourModel < ActiveRecord::Baseinclude ProstoCache
-
Configure cache access keys (optional step, by default cache is accessed by key ‘name’) cache_accessor_keys %w(scope name)
-
Your model must have non-nullable column updated_at, add it in migration if it is missing (this field is used for invalidating cache in other ruby processes).
-
Access cached model object in your code like this Simple case of one key
YourModel.cache[:key1]
Case of 2 or more keys
YourModel.cache[:key1, :key2, :key3]
-
Handling of non-existing cache values. If cache is accessed using symbol key and value not found, it will raise
BadCacheKeyError
. If cache is accessed using string key and value not found, it will return nil. For complex keys type of last key component is the one taken into account. -
If you want to, you can add extra lookup helpers to the objects that relate to the cached object, that will allow those objects to update ‘string’ attribute, and that will result in database reference change.
class OtherModel < ActiveRecord::Base belongs_to :your_model lookup_enum_for :your_model end
This lookup was intertionally not integrated ‘seamlessly’ with ActiveRecord since not everybody would want that, and monkey-patching other library (AR) is not really a good thing, even if it results in a ‘smoother’ experience where everything works as if by magic.
Public Class Methods
# File lib/prosto_cache/prosto_hash.rb, line 33 def self.fail_on_missing_value?(litmus) case litmus when Symbol true when String false else raise ArgumentError, "Unknown type of cache key #{litmus.inspect}" end end
# File lib/prosto_cache/prosto_model_cache.rb, line 208 def self.included(cl) cl.after_save { cl.cache.invalidate } class << cl def cache @cache ||= ProstoModelCache.new self, @accessor_keys, @sort_keys end def cache_accessor_keys(keys) @accessor_keys = keys end def cache_sort_keys(keys) @sort_keys = keys end end end