Class: Gravatar

Inherits:
Object
  • Object
show all
Defined in:
lib/gravatar.rb,
lib/gravatar/cache.rb

Overview

Errors ====

Errors usually come with a number and human readable text. Generally the text should be followed whenever possible, but a brief description of the numeric error codes are as follows:

-7  Use secure.gravatar.com
-8  Internal error
-9  Authentication error
-10 Method parameter missing
-11 Method parameter incorrect
-100  Misc error (see text)

Defined Under Namespace

Classes: Cache

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(email, options = {}) ⇒ Gravatar

Creates a new instance of Gravatar. Valid options include:

:password                   => the password for this account, to be used instead of :api_key (don't supply both)
:api_key or :apikey or :key => the API key for this account, to be used instead of :password (don't supply both)
:duration                   => the cache duration to use for this instance
:logger                     => the logger to use for this instance

Note that :password and :api_key are both optional. If omitted, no web services will be available but this user’s Gravatar image can still be constructed using #image_uri or #image_data.

Raises:

  • (ArgumentError)


28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/gravatar.rb', line 28

def initialize(email, options = {})
  raise ArgumentError, "Expected :email" unless email
  @options = options || {}
  @email = email

  pw_or_key = auth.keys.first || :none
  @cache = Gravatar::Cache.new(self.class.cache, options[:duration] || self.class.duration,
                               "gravatar-#{email_hash}-#{pw_or_key}", options[:logger] || self.class.logger)

  if !auth.empty?
    @api = XMLRPC::Client.new("secure.gravatar.com", "/xmlrpc?user=#{email_hash}", 443, nil, nil, nil, nil, true)
  end
end

Instance Attribute Details

#emailObject (readonly)

Returns the value of attribute email.



17
18
19
# File 'lib/gravatar.rb', line 17

def email
  @email
end

Class Method Details

.cacheObject



102
103
104
# File 'lib/gravatar/cache.rb', line 102

def cache
  @cache ||= default_cache_instance
end

.cache=(instance) ⇒ Object



106
107
108
# File 'lib/gravatar/cache.rb', line 106

def cache=(instance)
  @cache = instance
end

.default_cache_instanceObject



86
87
88
89
90
91
92
# File 'lib/gravatar/cache.rb', line 86

def default_cache_instance
  if defined?(Rails)
    Rails.cache
  else
    ActiveSupport::Cache::FileStore.new("tmp/cache")
  end
end

.default_logger_instanceObject



94
95
96
97
98
99
100
# File 'lib/gravatar/cache.rb', line 94

def default_logger_instance
  if defined?(Rails)
    Rails.logger
  else
    $stdout
  end
end

.durationObject

How long is a cached object good for? Default is 30 minutes.



119
120
121
# File 'lib/gravatar/cache.rb', line 119

def duration
  @duration ||= 24.hours
end

.duration=(duration) ⇒ Object



123
124
125
# File 'lib/gravatar/cache.rb', line 123

def duration=(duration)
  @duration = duration
end

.loggerObject



110
111
112
# File 'lib/gravatar/cache.rb', line 110

def logger
  @logger ||= default_logger_instance
end

.logger=(logger) ⇒ Object



114
115
116
# File 'lib/gravatar/cache.rb', line 114

def logger=(logger)
  @logger = logger
end

.reset_cache!Object

Resets any changes to the cache and initializes a new cache. If using Rails, the new cache will be the Rails cache.



129
130
131
# File 'lib/gravatar/cache.rb', line 129

def reset_cache!
  @cache = nil
end

.versionObject



198
199
200
# File 'lib/gravatar.rb', line 198

def self.version
  @version ||= File.read(File.join(File.dirname(__FILE__), "../VERSION")).chomp
end

Instance Method Details

#addressesObject

Gets a list of addresses for this account, returning a hash following this format:

{
  address => {
    :rating => rating,
    :userimage => userimage,
    :userimage_url => userimage_url
  }
}

This method is cached for up to the value of @duration or Gravatar.duration.



80
81
82
83
84
85
86
87
# File 'lib/gravatar.rb', line 80

def addresses
  cache('addresses') do
    call('grav.addresses').inject({}) do |hash, (address, info)|
      hash[address] = info.merge(:rating => rating(info[:rating]))
      hash
    end
  end
end

#cache_durationObject

The duration of the cache for this instance of Gravatar, independent of any other instance



43
44
45
# File 'lib/gravatar.rb', line 43

def cache_duration
  @cache.duration
end

#cache_duration=(time) ⇒ Object

Sets the duration of the cache for this instance of Gravatar, independent of any other instance



48
49
50
# File 'lib/gravatar.rb', line 48

def cache_duration=(time)
  @cache.duration = time
end

#delete_user_image!(userimage) ⇒ Object

Remove a userimage from the account and any email addresses with which it is associated. Returns true or false.

This method is not cached.

This method will clear out the cache, since it may have an effect on what the API methods respond with.



153
154
155
156
157
# File 'lib/gravatar.rb', line 153

def delete_user_image!(userimage)
  boolean(call('grav.deleteUserimage', :userimage => userimage)).tap do
    expire_cache!
  end
end

#email_hash(email = self.email) ⇒ Object

Returns the MD5 hash for the specified email address, or the one associated with this object.



166
167
168
# File 'lib/gravatar.rb', line 166

def email_hash(email = self.email)
  Digest::MD5.hexdigest(email.downcase.strip)
end

#exists?(*emails) ⇒ Boolean

Check whether one or more email addresses have corresponding avatars. If no email addresses are specified, the one associated with this object is used.

Returns: Boolean for a single email address; a hash of emails => booleans for multiple addresses.

This method is cached for up to the value of @duration or Gravatar.duration.

Returns:

  • (Boolean)


58
59
60
61
62
63
64
65
66
67
68
# File 'lib/gravatar.rb', line 58

def exists?(*emails)
  hashed_emails = normalize_email_addresses(emails)
  cache('exists', hashed_emails) do
    hash = call('grav.exists', :hashes => hashed_emails)
    if hash.length == 1
      boolean(hash.values.first)
    else
      dehashify_emails(hash, emails) { |value| boolean(value) }
    end
  end
end

#image_data(options = {}) ⇒ Object

Returns the image data for this user’s gravatar image. This is the same as reading the data at #image_url. See that method for more information.

This method is cached for up to the value of @duration or Gravatar.duration.



193
194
195
196
# File 'lib/gravatar.rb', line 193

def image_data(options = {})
  url = image_url(options)
  cache(url) { OpenURI.open_uri(URI.parse(url)).read }
end

#image_url(options = {}) ⇒ Object

Returns the URL for this user’s gravatar image. Options include:

:ssl     or :secure    if true, HTTPS will be used instead of HTTP. Default is false.
:rating  or :r         a rating threshold for this image. Can be one of [ :g, :pg, :r, :x ]. Default is :g.
:size    or :s         a size for this image. Can be anywhere between 1 and 512. Default is 80.
:default or :d         a default URL for this image to display if the specified user has no image;
                       or this can be one of [ :identicon, :monsterid, :wavatar, 404 ]. By default a generic
                       Gravatar image URL will be returned.
:filetype              an extension such as :jpg or :png. Default is omitted.

See en.gravatar.com/site/implement/url for much more detailed information.



181
182
183
184
185
186
187
# File 'lib/gravatar.rb', line 181

def image_url(options = {})
  secure = options[:ssl] || options[:secure]
  proto = "http#{secure ? 's' : ''}"
  sub = secure ? "secure" : "www"

  "#{proto}://#{sub}.gravatar.com/avatar/#{email_hash}#{extension_for_image(options)}#{query_for_image(options)}"
end

#remove_image!(*emails) ⇒ Object

Remove the userimage associated with one or more email addresses. Returns a hash of booleans.

NOTE: This appears to always return false, even when it is really removing an image. If you
know what the deal with that is, drop me a line so I can update this documentation!

This method is not cached.

This method will clear out the cache, since it may have an effect on what the API methods respond with.



139
140
141
142
143
144
145
# File 'lib/gravatar.rb', line 139

def remove_image!(*emails)
  hashed_email_addresses = normalize_email_addresses(emails)
  hash = call('grav.removeImage', :addresses => hashed_email_addresses)
  dehashify_emails(hash, emails) { |value| boolean(value) }.tap do
    expire_cache!
  end
end

#save_data!(rating, data) ⇒ Object Also known as: save_image!

Saves binary image data as a userimage for this account and returns the ID of the image.

This method is not cached.



105
106
107
# File 'lib/gravatar.rb', line 105

def save_data!(rating, data)
  call('grav.saveData', :data => Base64.encode64(data), :rating => _rating(rating))
end

#save_url!(rating, url) ⇒ Object

Read an image via its URL and save that as a userimage for this account, returning true or false

This method is not cached.



113
114
115
# File 'lib/gravatar.rb', line 113

def save_url!(rating, url)
  call('grav.saveUrl', :url => url, :rating => _rating(rating))
end

#test(hash) ⇒ Object

Runs a simple Gravatar test. Useful for debugging. Gravatar will echo back any arguments you pass. This method is not cached.



161
162
163
# File 'lib/gravatar.rb', line 161

def test(hash)
  call('grav.test', hash)
end

#use_user_image!(image_hash, *email_addresses) ⇒ Object Also known as: use_image!

Use a userimage as a gravatar for one or more addresses on this account. Returns a hash:

{ email_address => true/false }

This method is not cached.

This method will clear out the cache, since it may have an effect on what the API methods respond with.



123
124
125
126
127
128
129
# File 'lib/gravatar.rb', line 123

def use_user_image!(image_hash, *email_addresses)
  hashed_email_addresses = normalize_email_addresses(email_addresses)
  hash = call('grav.useUserimage', :userimage => image_hash, :addresses => hashed_email_addresses)
  dehashify_emails(hash, email_addresses) { |value| boolean(value) }.tap do
    expire_cache!
  end
end

#user_imagesObject

Returns a hash of user images for this account in the following format:

{ user_img_hash => [rating, url] }

This method is cached for up to the value of @duration or Gravatar.duration.



93
94
95
96
97
98
99
100
# File 'lib/gravatar.rb', line 93

def user_images
  cache('user_images') do
    call('grav.userimages').inject({}) do |hash, (key, array)|
      hash[key] = [rating(array.first), array.last]
      hash
    end
  end
end