Skip to content

Instantly share code, notes, and snippets.

@jeffreyiacono
Created November 4, 2011 16:03
Show Gist options
  • Save jeffreyiacono/1339702 to your computer and use it in GitHub Desktop.
Save jeffreyiacono/1339702 to your computer and use it in GitHub Desktop.
simple gravatar / avatar image model
class AvatarImage
GRAVATAR_IMAGE_BASE_URL = 'http://www.gravatar.com/avatar/'
GRAVATAR_IMAGE_DEFAULT_SIZE = '32'
DEFAULT_URL = 'http://your-awesome-domain.com/images/your-awesome-default-image.png'
attr_accessor :email
def self.default_url
DEFAULT_URL
end
def initialize(email)
@email = email
end
# if no email has been set, returns the default avatar url
# otherwise returns the generated gravatar_url
# options include:
# size => size of image to display, can be within the range "1" to "512"
# defaults to "32" if not specified.
# TODO: handle resizing of default avatar. as is, assumes the
# default size and / or passed option size will match default avatar
# imagess size. Could implement http://domain.com/images/avatar_{size}.png
# default => default image to display if no gravatar is found
# defaults to CW avatar man if not specified.
def url(options = {})
options[:default] ||= DEFAULT_URL
options[:size] ||= GRAVATAR_IMAGE_DEFAULT_SIZE
if @email.blank?
options[:default]
else
gravatar_url(options[:size], options[:default])
end
end
private
# return the gravatar image url for the specified email
# specify image size and default url if no image is found
def gravatar_url(size, default)
"#{GRAVATAR_IMAGE_BASE_URL}#{gravatar_email_hash}?s=#{size}&d=#{CGI.escape(default)}"
end
# generate the gravatar image based on their specifications:
# 1. Trim leading and trailing whitespace from an email address
# 2. Force all characters to lower-case
# 3. md5 hash the final string
# via: http://en.gravatar.com/site/implement/hash/
def gravatar_email_hash
Digest::MD5.hexdigest(@email.strip.downcase).to_s
end
end
@jeffreyiacono
Copy link
Author

example of usage in a view:
= image_tag AvatarImage.new(@comment.commenter_email).url

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment