Adding Caching Helper in Rails


When a particular API processing slow or performing a heavy calculation or have heavy DB queries. One of the solution to optimize the API that comes to our mind is to cache the response for appropriate amount of time. This will help us to improve the performance by overcoming the mentioned issues.

It is also important helper function like this which can be used across codebase should be written in a generic way for reusability of code. The DRY principle

While implementing a function which will hit the cache, we have to consider 2 cases. One what to do in case of hit and another is in case of miss. Incase of hit we can return the data as it is. But in case of miss, we should populate with the right data to avoid next miss. which can be achieved using following code

class CacheHelper
  def self.get_from_cache(key, callback_method, expire_time, *args)
    cache_data =
    if cache_data.blank?
      data =*args)
      Rails.cache.write(key, data, expires_in: expire_time)
      return data
    return cache_data

This method takes key, callback method to populate data, expiry time and arguments for the method.

Happing Learning!!

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *