eddorre

Rolled Out Gravatars

One of the things that I’ve had in mind when I started coding this blog in Rails was to eventually support Gravatars otherwise known as Globally Recognized Avatars.

Before rolling out this feature, comments had a little astronaut next to the speech bubble for each and every individual comment. If you have registered your email and uploaded a photo with the Gravatar service, it will no longer display the astronaut icon and it will load the registered image. If you haven’t registered, your comment gets a default kanji image.

Making this change in Rails was actually pretty trivial especially since Michael Mayo posted a very nice tutorial not long ago on his blog.

I did make some modifications from the code that he posted.

One of the more prominent changes that I made was to split out the image creation from the just generating the URL.

For example, I have this first method in my application_helper.rb file:


def gravatar_url_for(email, options = {})
      url_for({ :gravatar_id => Digest.MD5.hexdigest(email.downcase), :host => 'www.gravatar.com',
                   :protocol => 'http://', :only_path => false, :controller => 'avatar.php',
                   :default => 'http://eddorre.com/images/visitor.png',
                   :rating => 'G'}.merge(options))
end

I convert the email address to lowercase letters with the downcase method because an MD5 of noemail@eddorre.com and NOEMAIL@eddorre.com are actually two different things. This way, there can be no error. One of the other settings that I’m passing in is a “default” flag. If you haven’t registered with the Gravatar service, I’ll just use the astronaut image that I have and finally I don’t want goatse photos or worse showing up on my blog so I make the rating a mandatory “G”.

Notice that the above method doesn’t actually generate an image tag, it will only generate a URL.

For that, I have a second helper method defined simply as:


def gravatar_image(email, options = {})
      image_tag(gravatar_url_for(email, options), :alt => "Author Image")
end

This is the code that actually creates the Gravatar image.

Now in my view code, I can do the following (where @comment.email represents a variable with the user’s email address):


<%= gravatar_image(@comment.email, { :size => 40 }) %>

And it will display the image correctly. I should note that Michael’s example lists a size in height and width and you’ll notice that I’m passing the size as just an integer. I believe that the height and width options have been deprecated in favor of the more succinct size option.


Comments are closed

Comments are closed on this post. If you have something on your mind regarding this post, don't hesitate to drop me a line.