Shorts. by Jeff Kreeftmeijer

Ruby: One-line Gravatars without dependencies

Gravtastic is a popular library for adding Gravatars to Ruby applications. Using it is quite simple. You add it to your Gemfile, include it into the model you want to use it in, and call the is_gravtastic class method:

class User < ActiveRecord::Base
  include Gravtastic
  is_gravtastic
end

That will include Gravtastic::InstanceMethods into your model, giving you the gravatar_url method:

>> User.first.gravatar_url
=> "http://gravatar.com/avatar/9bc06f1049fb6069021854e14d9ec3c8.png"

There. Done. Or, can we improve on this some more? If we look at all the code we just included, I'd say we can. We can do better than “one file, about 80 LoC and really pretty simple”, right?

If we only need Gravatar urls without passing any options, this would do the exact same thing:

require 'digest'

class User < ActiveRecord::Base
  def gravatar_url
   "http://gravatar.com/avatar/#{Digest::MD5.hexdigest(email)}.png"
  end
end

If you need to pass extra options to request the right size or get a default image if the Gravatar does not exist, you add them as URL params:

class User < ActiveRecord::Base
  def gravatar_url
   "http://gravatar.com/avatar/#{Digest::MD5.hexdigest(email)}.png?size=200"
  end
end

There. One method, one LoC, the simplest thing that works, and probably all you ever need.