Skip to content

Instantly share code, notes, and snippets.

@jeffreyiacono
Created November 13, 2011 22:08
Show Gist options
  • Save jeffreyiacono/1362807 to your computer and use it in GitHub Desktop.
Save jeffreyiacono/1362807 to your computer and use it in GitHub Desktop.
simple gravatar / avatar image module, alternative to https://gist.github.com/1339702
module Avatarable
extend ActiveSupport::Concern
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'
# Avatarable assumes the class (or other module) that includes this module has an email attribute
# if the email attribute is named something other than email, use alias_attribute to map it to email
# alias_attribute :email, :your_email_attribute
module ClassMethods
end
module InstanceMethods
# return the default url, use when you want to just return the default image
# without checking for an email / gravatar
def default_avatar_url
DEFAULT_URL
end
# if no email value, 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 default avatar if not specified.
def avatar_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
end
@jeffreyiacono
Copy link
Author

sample usage:

model:

def Comment < ActiveRecord::Base
  include Avatarable
end

view:
- unless comment.anonymous? = image_tag comment.avatar_url - else = image_tag comment.default_avatar_url

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