Using Gravatars in Rails

September 15, 2019
Written by: Ted Martin
Gravatars are great ways to show user images in a Rails application. There are gems for adding this functionality but we can roll this for ourselves without adding a new dependency. The best part is, it only takes 7 lines of code.

First, let's create a helper class so that we can use this throughout an application:

module UsersHelper
  def gravatar_for(user)
    gravatar_id = Digest::MD5::hexdigest(
    gravatar_url = "{gravatar_id}"
    image_tag(gravatar_url, alt:, class: "gravatar")

All we need is an image_tag that uses a url for its first argument. The url is comprised of the default gravatar base url "" with a downcase version of the email address appended. I would suggest that a gem is not needed for something so simple.
Ted Martin

Husband, father, software developer, reader, writer. Seeking truth, goodness, and beauty.