The Spaghetti Refactory Established 2015

Very VERY basic Rails caching

If you're doing any sort of complex caching in Rails, you're probably not going to be using these below methods too much, but they're cool to know anyway.

Rails.cache.write(‘#{cache_key}’, object)
Rails.cache.read(‘#{cache_key}’) # => object
Rails.cache.exist?(‘#{cache_key}’) # => true

NOTE: This will NOT cache associations of that object. To do that, you would need to run:

object.associations.each do |assoc|
Rails.cache.write(‘#{assoc_cache_key}’, assoc)
Rails.cache.read(‘#{assoc_cache_key}’) # => assoc
Rails.cache.exist?(‘#{assoc_cache_key}’) # => true
end

You can set these caches to expire with certain options. More at http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html

Also, make sure you're aware that if you write to the same cache key with different data, it will simply overwrite that cache. It's good practice to use the object ID as part of the cache key for doing any sort of dynamic caching, unless you're just caching static content.

Tags