gravatar.rb

Gravatar Patch - Marcos Daniel Petry, 2009-03-06 14:26

Download (2.26 KB)

 
1
require 'digest/md5'
2
require 'cgi'
3

    
4
module GravatarHelper
5

    
6
  # These are the options that control the default behavior of the public
7
  # methods. They can be overridden during the actual call to the helper,
8
  # or you can set them in your environment.rb as such:
9
  #
10
  #   # Allow racier gravatars
11
  #   GravatarHelper::DEFAULT_OPTIONS[:rating] = 'R'
12
  #
13
  DEFAULT_OPTIONS = {
14
    # The URL of a default image to display if the given email address does
15
    # not have a gravatar.
16
    :default => nil,
17
    
18
    # The default size in pixels for the gravatar image (they're square).
19
    :size => 50,
20
    :s => 50,
21
    
22
    # The maximum allowed MPAA rating for gravatars. This allows you to 
23
    # exclude gravatars that may be out of character for your site.
24
    :rating => 'PG',
25
    :r => 'PG',
26
    
27
    # The alt text to use in the img tag for the gravatar.
28
    :alt => 'avatar',
29
    
30
    # The class to assign to the img tag for the gravatar.
31
    :class => 'gravatar',
32
  }
33
  
34
  # The methods that will be made available to your views.
35
  module PublicMethods
36
  
37
    # Return the HTML img tag for the given user's gravatar. Presumes that 
38
    # the given user object will respond_to "email", and return the user's
39
    # email address.
40
    def gravatar_for(user, options={})
41
      gravatar(user.email, options)
42
    end
43

    
44
    # Return the HTML img tag for the given email address's gravatar.
45
    def gravatar(email, options={})
46
      src = h(gravatar_url(email, options))
47
      options = DEFAULT_OPTIONS.merge(options)
48
      [:class, :alt, :size].each { |opt| options[opt] = h(options[opt]) }
49
      "<img class=\"#{options[:class]}\" alt=\"#{options[:alt]}\" width=\"#{options[:size]}\" height=\"#{options[:size]}\" src=\"#{src}\" />"      
50
    end
51

    
52
    # Return the gravatar URL for the given email address.
53
    def gravatar_url(email, options={})
54
      email_hash = Digest::MD5.hexdigest(email)
55
      options = DEFAULT_OPTIONS.merge(options)
56
      options[:default] = CGI::escape(options[:default]) unless options[:default].nil?
57
      returning "http://www.gravatar.com/avatar/#{email_hash}?" do |url| 
58
        [:r, :s, :default].each do |opt|
59
          unless options[opt].nil?
60
            value = h(options[opt])
61
            url << "&#{opt}=#{value}" 
62
          end
63
        end
64
      end
65
    end
66

    
67
  end
68
  
69
end