Posts Tagged ‘programming’

Gravatar Cache

Sunday, May 10th, 2009

Implementing Gravatar powered avatars is as simple as calculating a MD5 hash of the e-mail and loading the remote image at http://gravatar.com/avatar/[hash].

I needed a bespoke caching gravatar system, and decided to follow this simple approach:

  • Store all avatars as [hash].jpg
  • If [hash].jpg exists, and was created within a defined freshness period – use the stored avatar
  • Otherwise, load a new avatar from gravatar.

This method allows batch updating of avatars, which is useful for background batch jobs.

Desktop apps can use this as a local cache of images; while web apps can avoid extra external traffic.

My first attempt in ruby:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
require 'open-uri'
require 'md5'
 
$size="200"
$default="identicon"
$days=7
$dir="avatar"
 
def fill_gravatar_cache(email = null)
  cacheTime = Time.new - (60*60*24*$days)
  email.each() { |email|
    hash = MD5.md5(email).to_s
    fileName = $dir+"/"+hash+".jpg"
    if not (File.exists?(fileName) and
             File.ctime(fileName) > cacheTime)
      url = "http://gravatar.com/avatar/" +
             hash +
             "?s=" + $size +
             "&d=" + $default
      open($dir+"/" + hash + ".jpg","wb").
        write(open(url).read)
    end
  }
end

Thanks to auto un-boxing we can use a string or an array of strings. For example:

email = "an-email@address"
email = ["more","than","one","email","address"]

Planned extensions:

  • Update all avatars in the cache
  • Delete avatars that haven’t been used in a while
  • Store more than one size
  • Java and Flex implementations