If you want to show users gravatar profile picture in your rails application this article may help you Its very simple to use gravatar image in rails application by these simple steps

We need to create a helper method that returns Gravatar image for given user in your app/helpers/users_helper.rb as shown below

module UserHelper
  def user_gravatar(user)
    gravatar_id = Digest::MD5::hexdigest(user.eamil.downcase)
    gravatar_url = "http://secure.gravatar.com/avatar/#{gravatar_id}"
    image_tag(gravatar_url, alt: user.name)

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 in Digest library.

enter image description here

Email addresses are case insensitive but MD5 hashes are case sensitive so we have to use downcase method to ensure that the argument to hexdigest is lower case.

Then in views you can use <%= user_gravatar @user %> to show user gravatar profile image where ever you want

In app/users/show.html.erb

<% provide(:title, @user.name) %>
<div class="row">
  <aside class="col-md-4">
    <section class="user_info">
        <%= user_gravatar @user %>
        <%= @user.name %>

If user doesn't have gravatar image in that case it will show gravatar default image

We can also add CSS class and image size to gravatar image_tag in user_gravatar helper method

module UserHelper
  def user_gravatar(user, size: 80)
    gravatar_id = Digest::MD5::hexdigest(user.eamil.downcase)
    gravatar_url = "http://secure.gravatar.com/avatar/#{gravatar_id}?s=#{size}"
    image_tag(gravatar_url, alt: user.name, class: "profile-pic")

Hope its help full, thanks for reading, have a nice day.

Your comment