Display Avatar in Ruby on Rails application

June 17, 2011
Fuad

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:

gravatar_id = Digest::MD5.hexdigest(user.email.downcase)

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:

def avatar_url(user)
default_url = "#{root_url}images/default-image.jpg"
if(user.present?)
gravatar_id = Digest::MD5.hexdigest(user.email.downcase)
return "http://gravatar.com/avatar/#{gravatar_id}.png?s=48&d=#{CGI.escape(default_url)}"
else
return default_url
end
end

In your view:

<%= link_to(image_tag(avatar_url(user)), user_path(user.id))%>

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

Tags: Ruby on Rails,

No comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.