Rails Model Caching with Redis

Hi Vasu,

I think you are definitely on the right track but you have missed a trick which will make your code much cleaner, namely Rails.cache.

This rails class ties in to the config.cache_store that you set earlier and allows you to access the cache by using Rails.cache in your code so you no longer need to set up the $redis initializer and any time you want to swap out your cache backend you can easily do so.

This also means that you know have access to Rails.cache.fetch which takes a key and then any optional options and then a value or a block. In the case of a block, calling Rails.cache.fetch will first check the cache using the key provided and it doesn’t find anything in the cache then it executes the do block and sets the cache to whatever the block yields.

So your helper would be reduced to something like the following.

@categories = Rails.cache.fetch("categories") do
  Category.all
end

To add a time based expiry you just add in the time as an option.

@categories = Rails.cache.fetch("categories", expires_in: 5.minutes) do
  Category.all
end

You can also clear the specific cache by passing in the key.

Rails.cache.delete("categoriess")

I would defintely recommend checking out http://guides.rubyonrails.org/caching_with_rails.html for more information.