Written by Sean Behan on Fri Apr 11th 2014

To get a Gravatar you need to hash an email address with the MD5 algorithm.

MD5 is a part of the Ruby standard library. Rails loads it by default, but otherwise you will have to require it yourself.

This is a simple implementation.

Gravatar supports other features, such as ratings and sizes. But the code below just hashes an email and constructs the Gravatar URL.

It also sets a default image using the ?d param, in case you need a default image.

require 'digest/md5'
# gravatar("someone@example.com")
def gravatar(email)
    base_url = "http://gravatar.com/avatar/"
    hashed_email = Digest::MD5.hexdigest(email)
    default_image =  "?d=http://example.com/path/to/default-image.jpg"
    [base_url, hashed_email, default_image].join

The image I used for the default doesn't exist. Replace it with your own default image.

Tagged with..
#ruby #gravatar #images

Just finishing up brewing up some fresh ground comments...