Skip to content

Instantly share code, notes, and snippets.

@stefl
Created May 10, 2013 11:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefl/5553821 to your computer and use it in GitHub Desktop.
Save stefl/5553821 to your computer and use it in GitHub Desktop.
Use memcache on repetitive avatar requests in Rails
def avatar(options = {})
key = "avatar-#{nickname}-#{options.map {|k,v| "#{k}:#{v}" }.join("-")}"
cached_avatar = Rails.cache.fetch(key)
return cached_avatar if cached_avatar
options.reverse_merge!({size: 48})
unless model.nil?
avatar = h.link_to(h.person_path(model)) do
h.image_tag(avatar_address,
class: 'avatar__img',
data: { src: avatar_address },
alt: nickname,
title: nickname,
height: options[:size],
width: options[:size])
end
Rails.cache.write(key, avatar)
avatar
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment