Personalizing User Profiles with Gravatars

Problem

Contributed by: Nicholas Wieland

You want to allow users to personalize their presence on your site by displaying small user images associated with each user's comments and profiles.

Solution

Use gravatars (globally recognized AVATAR) or small 80 x80 images that are associated with users by email address. The images are stored on a remote server, rather than your application's site. Users register for a gravatar once, allowing their user image to be used on all gravatar-enabled sites.

To make your application gravatar-enabled, define a method that returns the correct link from inside the ApplicationHelper:

app/helpers/application_helper.rb:

require "digest/md5" 
module ApplicationHelper
 def url_for_gravatar(email) 
 gravatar_id = Digest::MD5.hexdigest( email ) 
 "http://www.gravatar.com/avatar.php?gravatar_id=#{ gravatar_id }" 
 end 
end

Your views can use this helper in a very simple way. Just use url_for_gravatar to build the URL of an image tag. In the following code, @user.email holds the email address of the gravatar's owner:

<%= image_tag url_for_gravatar(@user.email) %>

Discussion

Using gravatars is simple: you have to use an <img /> tag where you want to display the gravatar, with a src attribute pointing to the main gravatar site, including the MD5 hash of the gravatar owner's email. Here's a typical gravatar URL:

http://www.gravatar.com/avatar.php\
 ?gravatar_id=7cdce9e94d317c4f0a3dcc20cc3b4115

In the event that a user doesn't have a gravatar registered, the URL returns a 1 x1 transparent GIF image.

The url_for_gravatar helper method works by calculating the MD5 hash of the email address passed to it as an argument; it then returns the correct gravatar URL using string interpolation.

The Gravatar service supports some options that let you avoid manipulating images within your application. For example, by passing the service a size attribute, you can resize the gravatar to something other than 80 x80 (for example, size=40).

See Also