I wrote a gravatar helper to use in my learning app. The Users#index action lists all users with their gravatars, which can take a while even with pagination. Is there a way to cache the gravatars in Rails 3.2 with the following in mind:
- Without using a Gravatar plugin that has a cache feature.
-
Without caching the users page itself; really, I’m only looking to cache the images themselves without having to grab them from gravatar.com again.
def gravatar_for(user, options = { size: 50 }) gravatar_id = Digest::MD5::hexdigest(user.email.downcase) size = options[:size] gravatar_url = "http://gravatar.com/avatar/#{gravatar_id}.png?s=#{size}" image_tag(gravatar_url, alt: user.name) end
Caching the entire users page or fragment caching the image urls wouldn’t make a difference anyway because the images will still be downloaded from Gravatar. Gravatar sets their
Cache-Controlheader to have a max age of 5 minutes and there’s not much else you can do about it.One possibility is to save the images to another location where you have control over the response headers.
One minor thing you could do during development though is to not use a hard refresh on your pages. In some browsers
CMD/CTRL + Ror pressing the refresh button sends request headers withCache-Control:max-age=0which causes you to re-download all the images. You can do a soft refresh by simply visiting the page again (for example: pressing enter on the url in the addressbar) and it won’t send that header.