« Parallels Desktop: Mac Web De... « » Fight Spam With JavaScript »

Adding Gravitar To Your Website Or Blog (In under 30 seconds)

Michael Deering April 16th, 2008

Bells and whistles are always fun, so when whipping together this blog I wanted to try my hand at adding a few. First “nice-to-have” I went after was adding Gravitar to the comments. I did not really expect to much of a challenge but I had no idea it would be this straightforward.

Extend the string class a little.

# config/initializers/string_extensions.rb
class String

  def md5
    Digest::MD5.hexdigest(self)
  end

  def uri_encode
    URI.escape(self, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
  end

end

Add a few constants for cleanup.

# config/initializers/constants.rb
GRAVITAR_BASE_URL = 'http://www.gravatar.com/avatar.php'
GRAVITAR_DEFAULT_IMAGE = "http://#{HOST}/images/default_gravitar.gif" 
GRAVITAR_SIZE = 40

And of course add in your view helper.

# app/helpers/application_helper.rb
def gravitar_image_tag(email, html_options = {})
  image_tag gravitar_url(email), html_options
end

private
  def gravitar_url(email)
    return GRAVITAR_DEFAULT_IMAGE if email.nil?
    "#{GRAVITAR_BASE_URL}?gravatar_id=#{email.md5}&default=#{GRAVITAR_DEFAULT_IMAGE.uri_encode}&size=#{GRAVITAR_SIZE}" 
  end

That is it… done! Start calling it from your views.


gravitar_image_tag comment.email

Tags

4 comments so far

Avatar by Juan Pablo 9 hours later

This is nice! and the comment a test.

Avatar by mike 20 hours later

This would be a nice helper tag if it was all wrapped up as “gravatar_image_tag”.

Avatar by Michael Deering 1 day later

@mike

Your right was not sure on its use when I started but that makes sense to me. Updated the code and post to reflect your suggestion.

Avatar by ramsesoriginal 2 weeks later

That’s cool. A beautiful improvement would be to have “dynamic” default images, for example based on the nationality of the user (based on ip adress), on the number of posts, or whatever. But this shouldn’t be that much of a challenge.

Post A Comment


Or I will pick one for you!

For that cool little Gravitar icon!

You shameless self promoter!


Format with Textile if you wish.