I found a better way to do this! Go to the article at /2010/01/26/gravatar-default-images-a-better-way/ and read that instead!

I wanted to add Avatars to my new project whatiwantforxmas.com but it felt like too much hard work. So, I took a leaf out of githubs book and used Gravatars.

Gravatars are an already pre-packaged avatar system, all bright and shiny and ready to be added to your application.

If you haven’t got a Gravatar do me a favour, go over to gravatar.com and signup

It’s ridiculously easy to put in your app!

I use Scott Woods nice little Gravatar plugin – you can install it in your Rails app thusly:

  
        script/plugin install svn://rubyforge.org/var/svn/gravatarplugin/plugins/gravatar  
        

Here’s how you use it, bung this into your view (where user is an object that has an email attribute):

  
        gravatar_for(user)  
        

And BOO YA – you’ve got an instant gravatar image on your page!

You could also call by passing in an email address (but it’s not so sexy):

  
        gravatar(user.email)  
        gravatar("jim@banana.com")  
        

You can even set which size you want! (As in this case 50px x 50px)

  
        gravatar(user.email, :size => 50)  
        

“But wait! What if the user doesn’t HAVE a Gravatar?!” Well, then a default image is used instead. Typically something nasty like this:

But dry your eyes, all is not lost. You can set your own default Gravatar!
When you call the Gravatar method just pass in a :default param pointing to the default image you want to use.

  
        gravatar_for(user, :size => 50, :default =>  
         "http://www.whatiwantforxmas.com/images/avatars/santa/santa-50.png")
        

I wasn’t into the scaling of the default images though, so I wrote this little snippet of code so that you can have a separate default image for each Gravatar size you want. This ensures that I only use Gravatars that are 25, 50 or 70px (the sizes that I have default images for).

Copy this code into a file in your lib folder, and don’t forget to ‘require’ it in an initializer.

  
        module GravatarHelper  
          module PublicMethods
            AVATAR_SIZES = [25, 50, 70]
        
            def gravatar_for_with_default(object, options={})
             options[:size] ||= 25      
             options.merge!(:default =>  "http://www.whatiwantforxmas.com/images/avatars/santa/santa-#{options[:size]}.png")      
             # sizes are 25, 50 and 70
             raise RuntimeError, "Incorrect size for Avatar" \
                 unless AVATAR_SIZES.index(options[:size])    
             gravatar_for_without_default(object, options)
           end
           alias_method_chain :gravatar_for, :default
        end  
        end  
        

And then I just need to call it like this:

  
        # This will use my default avatar
        gravatar_for(user, :size => 50)  
        

PS Yeah, I know I know – my blog doesn’t use Gravatars yet…