Add Gravatars to your Rails Application
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.
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/gravatarHere’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:
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…