Last active
August 29, 2015 14:00
-
-
Save tlux/11368281 to your computer and use it in GitHub Desktop.
Gravatar Image Tag Helper for your Rails Application
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_accessor(*VALID_OPTIONS) | |
| alias_method :force_default?, :force_default | |
| alias_method :secure?, :secure | |
| def initialize(email, options = {}) | |
| @email = email.strip.downcase | |
| options = options.assert_valid_keys(*VALID_OPTIONS).reverse_merge(DEFAULTS) | |
| options.each do |key, value| | |
| send("#{key}=", value) | |
| end | |
| end | |
| def digest | |
| Digest::MD5.hexdigest(@email) | |
| end | |
| def url | |
| base_url = (secure? ? SECURE_URL : INSECURE_URL) % { hash: digest } | |
| uri = URI.parse(base_url) | |
| params = {} | |
| params[:s] = size unless size.nil? | |
| params[:d] = (default == :not_found) ? '404' : default unless default.nil? | |
| params[:f] = 'y' if force_default? | |
| params[:r] = rating unless 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