lib/img_gravatar.rb in img_gravatar-0.1.1 vs lib/img_gravatar.rb in img_gravatar-0.2.0

- old
+ new

@@ -1,15 +1,20 @@ -require 'md5' +DIGEST_INTERFACE = begin + require 'md5' + :ruby18 +rescue LoadError + require 'digest/md5' + :ruby19 +end + require 'uri' require 'action_view' -# = Gravatar +# = ImgGravatar # # Adds the +gravatar+ method to ActionViews. -# -# $Id$ -module ImgGravatar #:nodoc: +module ImgGravatar mattr_reader :gravatar_host @@gravatar_host = 'www.gravatar.com' # gravatar.com base URL. # This is +http://www.gravatar.com/avatar/+. mattr_reader :gravatar_base_url @@ -34,26 +39,28 @@ @@default_rating = 'g' ############################################################################ # get the Gravatar image. # options: - # :alt - the alternative text for this image + # :alt - the alternative text for this image (img attribute) # :default_url - the default URL for this gravatar - # :size - the requested gravatar size + # :size - the requested gravatar size (img attribute, gravatar-attribute) # :rating - the requested maximum rating def self.link_gravatar(email, opts={}) # the defaults - alt = nil - alt = opts[:alt] if opts[:alt] - - if alt then - "<img src=\"%s\" alt=\"%s\" />" % [image_url(email, opts), alt] + tag_options = {} + tag_options[:alt] =opts[:alt] if opts[:alt] + tag_options[:size] =opts[:size] if opts[:size] && (opts[:size] >= 1 && opts[:size] <= 512) + + unless tag_options.empty? + attributes = tag_options.collect {|key, value| "#{key}=\"#{value}\"" }.join(" ") + "<img src=\"%s\" %s />" % [image_url(email, opts), attributes] else "<img src=\"%s\" />" % image_url(email, opts) end end - + ############################################################################ # get the default Gravatar image. # options: # :default_url - the default URL for this gravatar # :size - the requested gravatar size @@ -73,14 +80,29 @@ query = URI.escape(query) if query #uri = URI::HTTP.new(Gravatar.gravatar_base_url) uri = URI::HTTP.build(:host => ImgGravatar.gravatar_host, - :path => "/avatar/%s" % MD5.md5(email.downcase.strip), + :path => "/avatar/%s" % encode_md5(email), :query => query) end - + + # encode an EMail for Gravatar. + # This will basically take any string, strip is, and hash the result + # using MD5. + def self.encode_md5(email) + value = email.downcase.strip + case DIGEST_INTERFACE + when :ruby18 + return MD5.md5(value) + when :ruby19 + return Digest::MD5.hexdigest(value) + else + raise "unknown Ruby Digest interface." + end + end + # Methods injected in all ActionView classes. module Base #:nodoc: def self.included(mod) #:nodoc: mod.extend(ClassMethods) end @@ -92,10 +114,11 @@ class_eval do include Gravatar::InstanceMethods end end end - + + # Methods available in ActionView. module InstanceMethods ############################################################################ # get the Gravatar image. # See ImgGravatar.link_gravatar for options. def img_gravatar(email, opts={})