Published On: June 17th, 20111.6 min read

Now a days displaying Avatar is a common trend in web technology. Avatar is graphical representation of an user. Thanks go to Tom Preston Werner for introducing Gravatar, a great web service which give globally recognized avatar. You just need to open up an account out their with an email address and upload your photo. Different websites, consuming Gravatar’s service can display your photo if you register out there with the same email address.In this example I will show you a way to display Gravatar in your Ruby on Rails web application.

First I will write a helper method which will return an image url for displaying Avatar. Gravater, id is simply the MD5 hexdigest of the email address.

So the line returning avatar id will be:

[sourcecode language=”ruby”] gravatar_id = Digest::MD5.hexdigest([/sourcecode]

I would like to display the avatar as 48×48, which is the usual size of a twitter display image. Also, I want to show a default image url if avatar is not shown. For these two, we need to pass some extra parameters. The method will look like:

[sourcecode language=”ruby”] def avatar_url(user)
default_url = “#{root_url}images/default-image.jpg”
gravatar_id = Digest::MD5.hexdigest(
return “{gravatar_id}.png?s=48&d=#{CGI.escape(default_url)}”
return default_url

In your view:

[sourcecode language=”ruby”] [/sourcecode]

The above line, will show the avatar and will take you to the show method of UsersController if you click on it.

You can also choose from an user to display his avatar from gravatar or your local file system. All you need to do is to have a boolean field ‘avatar’ in your User table and re-arrange the logic in avatar_url method.

It’s that simple! Happy coding!!

Contributor: Fuad Bin Omar, COO, Nascenia

Share it, Choose Your Platform!

More to Explore

The Quest for Knowledge Continues. Fuel Your Curiosity.