Gravatar (Globally Recognized Avatar) is a free service that allows users to upload images and associate them with email addresses they control, it’s an image that follows you from site to site appearing beside your name when you do things like comment or post on a blog. Gravatars are a convenient way to include user profile images without going through the trouble of managing image upload, cropping, and storage; all we need to do is construct the proper Gravatar image URL using the user’s email address and the corresponding Gravatar image will automatically appear.

Here we go, we will try simple usage of Gravatar in Ruby on Rails. It’s simple because Gravatar ‘APIs’ require no authentication, and are all based around simple HTTP GET requests, you don’t even need an account. And in order to follow this tutorial, you can use exiting project or create new project since we will use Users controller in this case. For new project, you can use scaffold:

$ rails generate scaffold Users name:string email:string

First, locate your UsersHelper at \app\helpers\users_helper.rb

module UserHelper  
end  

Write new mothod for gravatar.

module UsersHelper  
  # return Gravatar to given user
  def gravatar(user)
  end
end  

First we need to get the email from URL. As noted at the Gravatar home page, Gravatar URLs are based on an MD5 hash of the user’s email address. In Ruby, the MD5 hashing algorithm is implemented using the hexdigest method, which is part of the Digest library:

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

Since email addresses are case-insensitive but MD5 hashes are not, we’ve used the downcase method to ensure that the argument to hexdigest is all lower-case.

Create URL based on user id:

gravatar_url = "http://www.gravatar.com/avatar/#{gravatar_id}"  

Last, use image_tag to display the avatar:

image_tag(gravatar_url, alt: user.name, class: "gravatar")  

Let’s wrap it up, this is method for our Gravatar:

module UsersHelper  
  # return Gravatar to given user
 def gravatar(user)
    gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
    gravatar_url = "http://www.gravatar.com/avatar/#{gravatar_id}"
    image_tag(gravatar_url, alt: user.name, class: "gravatar")
  end
end  

Put the Gravatar in \app\views\users\show.html.erb

# Call User's Gravatar
<%= gravatar @user %>

<div>  
  <strong>Name:</strong>
  <%= @user.name %>
</div>

<div>  
  <strong>Email:</strong>
  <%= @user.email %>
</div>  

That’s all, let’s run rails server and our work:

User Signup

Showing User With Gravatar


Written by Irfan Fadilah – Author at 41studio

Read more at the source