gravatar for rails app

module UsersHelper

  # Rails cookbook p 190
  def url_for_gravatar(email)
    gravatar_id = Digest::MD5.hexdigest( email )
    "http://www.gravatar.com/avatar.php?gravatar_id=#{ gravatar_id }"
  end

end

Comments

  1. Scott Motte | July 21, 2008

    Update: The rails cookbook solution just isn’t that great. You can’t specify a default.

    Much better solution

    module GravatarHelper
    # Returns a Gravatar URL associated with the email parameter.
    def gravatar_url(email,gravatar_options={})

    # Default highest rating.
    # Rating can be one of G, PG, R X.
    # If set to nil, the Gravatar default of X will be used.
    gravatar_options[:rating] ||= nil

    # Default size of the image.
    # If set to nil, the Gravatar default size of 80px will be used.
    gravatar_options[:size] ||= nil

    # Default image url to be used when no gravatar is found
    # or when an image exceeds the rating parameter.
    gravatar_options[:default] ||= ‘http://localhost:3000/images/gravatar-80.png’

    # Build the Gravatar url.
    grav_url = ‘http://www.gravatar.com/avatar.php?’
    grav_url << “gravatar_id=#{Digest::MD5.new.update(email)}”
    grav_url << “&rating=#{gravatar_options[:rating]}” if gravatar_options[:rating]
    grav_url << “&size=#{gravatar_options[:size]}” if gravatar_options[:size]
    grav_url << “&default=#{gravatar_options[:default]}” if gravatar_options[:default]
    return grav_url
    end

    end