Skip to content

Instantly share code, notes, and snippets.

@lwe
Created September 16, 2009 13:07
Show Gist options
  • Save lwe/188029 to your computer and use it in GitHub Desktop.
Save lwe/188029 to your computer and use it in GitHub Desktop.
Some simple helpers to construct gravatar urls and <img/>-tags.
module Gravatar
def self.options; @options ||= {}; end
module GravatarHelper
def gravatar_url(mail, options = {})
options = Gravatar.options.merge(options).stringify_keys!
options.assert_valid_keys('size', 'rating', 'default')
"#{build_gravatar_host(mail)}/avatar/#{Digest::MD5.hexdigest(mail.to_s.strip.downcase)}.jpg#{build_gravatar_url_options(options)}"
end
def gravatar_tag(mail, options = {})
gravatar_opts = { :size => options[:size] ||= Gravatar.options[:size] || 80, :default => options.delete(:default), :rating => options.delete(:rating) }
options[:size] = "#{options[:size]}x#{options[:size]}"
options[:alt] ||= mail
image_tag(gravatar_url(mail, gravatar_opts), options)
end
private
def build_gravatar_host(mail, secure = false)
secure ? "https://secure.gravatar.com" : "http://#{%w{0 1 2 www}[mail.length % 4]}.gravatar.com"
end
def build_gravatar_url_options(options = {})
url_opts = []
url_opts << "s=#{CGI.escape(options['size'].to_s)}" if options['size'].to_i > 0
url_opts << "r=#{CGI.escape(options['rating'].to_s.downcase)}" if options['rating']
url_opts << "d=#{CGI.escape((options['default'].respond_to?(:call) ? options['default'].call(options) : options['default']).to_s)}" if options['default']
"?" << url_opts.join('&') unless url_opts.empty?
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment