Quantcast
Viewing all articles
Browse latest Browse all 2

Answer by Marcus for How to store nil with Rails.cache.fetch & memcache?

One solution is to use a NullObject, like this:

class Specialist
  NullData = Struct.new(nil)

  def city
    result = Rails.cache.fetch([self.class.name, self.id, "city"], expires_in: 23.hours) do
      if responded?
        ..
      else
        NullData.new()
      end
     result.is_a?(NullData) ? nil : result 
   end
end

That way you create a null object that can be cached. Then when you return you check if it's a null object that has been stored, in that case you return nil (to make sure you don't break your old code that relies on your method returning nil), else you return the cached content.


Viewing all articles
Browse latest Browse all 2

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>