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 Gravitar 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
GRAVITAR_BASE_URL = 'http://www.gravatar.com/avatar.php'
GRAVITAR_DEFAULT_IMAGE = "http://#{HOST}/images/default_gravitar.gif"
GRAVITAR_SIZE = 40
And of course add in your view helper.
# app/helpers/application_helper.rb
def gravitar_image_tag(email, html_options = {})
image_tag gravitar_url(email), html_options
end
private
def gravitar_url(email)
return GRAVITAR_DEFAULT_IMAGE if email.nil?
"#{GRAVITAR_BASE_URL}?gravatar_id=#{email.md5}&default=#{GRAVITAR_DEFAULT_IMAGE.uri_encode}&size=#{GRAVITAR_SIZE}"
end
That is it… done! Start calling it from your views.
gravitar_image_tag comment.email



