Last active
August 29, 2015 14:09
-
-
Save tlux/429ca485a142b8d304d7 to your computer and use it in GitHub Desktop.
Lightweight Gravatar Implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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