Tag Archives: Gravatar

Gravatars on Rails


Gravatar is the globally recognized avatar run by the folks who run WordPress.com.

Your Gravatar is an image that follows you from site to site appearing beside your name when you do things like comment or post on a blog. This is done by associating an image to the users email address. Adding Gravatar to PriceChirp seemed like a fun thing to do.

The API is very simple, so adding it to a Ruby on Rails site is easy.

First, add a few lines to your application-helper.rb:

  def gravatar_url_for(email, options = {})
    url_for({
      :gravatar_id => Digest::MD5.hexdigest(email),
      :host => 'www.gravatar.com',
      :protocol => 'http://',
      :only_path => false,
      :skip_relative_url_root => true,
      :controller => '/avatar'
    }.merge(options)
    )
  end

You may also need to add:

require 'digest/md5'

Now you can add the gravatar to your views like this:

  # standard gravatar url
  <%= gravatar_url_for 'user@gmail.com' %>

  # gravatar url with a rating threshold
  <%= gravatar_url_for 'user@gmail.com', { :rating => 'R' } %>

  # show the avatar
  <%= image_tag(gravatar_url_for 'email@gmail.com')%>

  # change the size of the avatar
  <%= image_tag(gravatar_url_for('email@gmail.com', { :size => 30 })) %>

Note: Gravatar is case sensitive on the user’s email address. They will match against an all lower case version of the email address. If you need to allow uppercase characters in your email addresses, you will need to .downcase the email address in the view or helper. I do not have this requirement, so I fix the case in the user.rb model at save time:

  before_save :fix_email_case

  protected

  def fix_email_case
    if !self.email.nil?
      self.email.downcase!
    end
  end