17 June 2011

Display Avatar in Ruby on Rails application

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 48x48, 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!!



1 comment:

rasal said...

I really loved reading your blog. It was very well authored and easy to understand. Unlike additional blogs I have read which are really not tht good. I also found your posts very interesting.
ptc