This repository has been archived by the owner on Nov 17, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 69
/
gravtastic.rb
91 lines (67 loc) · 1.87 KB
/
gravtastic.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
require 'digest/md5'
require 'cgi'
require 'uri'
module Gravtastic
def self.included(base)
base.extend(SingletonMethods)
end
module SingletonMethods
def is_gravtastic(source = :email, options={})
extend ClassMethods
include InstanceMethods
if source.is_a?(Hash)
options = source
source = :email
end
@gravatar_defaults = {
:rating => 'PG',
:secure => false,
:filetype => :png
}.merge(options)
@gravatar_source = source
end
alias_method :has_gravatar, :is_gravtastic
alias_method :is_gravtastic!, :is_gravtastic
end
module ClassMethods
# attr_reader :gravatar_source, :gravatar_defaults
def gravatar_source
@gravatar_source
end
def gravatar_defaults
@gravatar_defaults
end
def gravatar_options
{
:size => 's',
:default => 'd',
:rating => 'r'
}
end
end
module InstanceMethods
def gravatar_id
Digest::MD5.hexdigest(send(self.class.gravatar_source).to_s.downcase)
end
def gravatar_url(options={})
options = self.class.gravatar_defaults.merge(options)
gravatar_hostname(options.delete(:secure)) +
gravatar_filename(options.delete(:filetype)) +
url_params_from_hash(options)
end
private
def url_params_from_hash(hash)
'?' + hash.map do |key, val|
[self.class.gravatar_options[key.to_sym] || key.to_s, CGI::escape(val.to_s) ].join('=')
end.sort.join('&')
end
def gravatar_hostname(secure)
'http' + (secure ? 's://secure.' : '://') + 'gravatar.com/avatar/'
end
def gravatar_filename(filetype)
"#{gravatar_id}.#{filetype}"
end
end
end
ActiveRecord::Base.send(:include, Gravtastic) if defined?(ActiveRecord) # :nodoc:
DataMapper::Resource.append_inclusions(Gravtastic) if defined?(DataMapper) # :nodoc: