Skip to content

Instantly share code, notes, and snippets.

@tlux
Last active August 29, 2015 14:09
Show Gist options
  • Select an option

  • Save tlux/429ca485a142b8d304d7 to your computer and use it in GitHub Desktop.

Select an option

Save tlux/429ca485a142b8d304d7 to your computer and use it in GitHub Desktop.
Lightweight Gravatar Implementation
class Gravatar
DEFAULTS = {
default: :not_found,
force_default: false,
size: 100,
secure: false
}.freeze
INSECURE_URL = "http://www.gravatar.com/avatar/%{hash}"
SECURE_URL = "https://secure.gravatar.com/avatar/%{hash}"
VALID_OPTIONS = :size, :default, :rating, :secure, :force_default
attr_reader :email, :size, :default, :rating
attr_writer *VALID_OPTIONS
def initialize(email, options = {})
@email = email.strip.downcase
options.assert_valid_keys(*VALID_OPTIONS).reverse_merge(DEFAULTS).each do |key, value|
self.send("#{key}=", value)
end
end
def digest
Digest::MD5.hexdigest(email)
end
def force_default?
@force_default
end
def secure?
@secure
end
def url
base_url = (self.secure? ? SECURE_URL : INSECURE_URL) % { hash: self.digest }
uri = URI.parse(base_url)
params = {}
params[:s] = self.size unless self.size.nil?
unless self.default.nil?
params[:d] = (self.default == :not_found) ? '404' : self.default
end
params[:f] = 'y' if self.force_default?
params[:r] = self.rating unless self.rating.nil?
uri.query = params.to_query.presence
uri.to_s
end
end
module GravatarHelper
def gravatar_image_tag(email, options = {})
html_options = options.except(*Gravatar::VALID_OPTIONS).deep_dup
html_options[:alt] ||= email
html_options[:class] = ['gravatar', *html_options[:class]].compact
url_options = options.slice(*Gravatar::VALID_OPTIONS).reverse_merge(secure: request.ssl?)
url_options.reverse_merge!(Gravatar::DEFAULTS)
size = url_options[:size]
html_options.reverse_merge!(width: size, height: size) if size
image_tag gravatar_image_url(email, url_options), html_options
end
def gravatar_image_url(email, options = {})
Gravatar.new(email, options.reverse_merge(secure: request.ssl?)).url
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment