Adding Gravatar To Your Website Or Blog (In under 30 seconds)
Update This has all been wrapped up into a much friendlier and configurable rails plugin over on Github. gravatar_image_tag plugin
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 Gravatar 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
GRAVATAR_BASE_URL = 'http://www.gravatar.com/avatar.php'
GRAVATAR_DEFAULT_IMAGE = "http://#{HOST}/images/default_gravatar.gif"
GRAVATAR_SIZE = 40
And of course add in your view helper.
# app/helpers/application_helper.rb
def gravatar_image_tag(email, html_options = {})
image_tag gravatar_url(email), html_options
end
private
def gravatar_url(email)
return GRAVATAR_DEFAULT_IMAGE if email.nil?
"#{GRAVATAR_BASE_URL}?gravatar_id=#{email.md5}&default=#{GRAVATAR_DEFAULT_IMAGE.uri_encode}&size=#{GRAVATAR_SIZE}"
end
That is it… done! Start calling it from your views.
gravatar_image_tag comment.email
Update This has all been wrapped up into a much friendlier and configurable rails plugin over on Github. gravatar_image_tag plugin
