9

using this gem https://github.com/sinisterchipmunk/gravatar how do i check if gravatar for specified email exist or not? I think i am missing some force default option? Because this

url = Gravatar.new("generic@example.com").image_url

always return a picture

Jakub Kuchar
  • 1,665
  • 2
  • 23
  • 39

3 Answers3

44

In case people would like to know how to do it without any gems :

The trick is to get gravatar image with a false default image and then check header response. It's achieved with the Net::HTTP ruby library.

require 'net/http'

def gravatar?(user)
    gravatar_check = "http://gravatar.com/avatar/#{Digest::MD5.hexdigest(user.gravatar_email.downcase)}.png?d=404"
    uri = URI.parse(gravatar_check)
    http = Net::HTTP.new(uri.host, uri.port)
    request = Net::HTTP::Get.new(uri.request_uri)
    response = http.request(request)
    response.code.to_i != 404 # from d=404 parameter
end
scarver2
  • 7,887
  • 2
  • 53
  • 61
Noémien Kocher
  • 1,324
  • 15
  • 17
8

Looking at that gem's documentation, it sounds like you need an API key before you can run the exists method:

Fine, but how about the rest of the API as advertised at en.gravatar.com/site/implement/xmlrpc? Well, for that you need either the user’s Gravatar password, or their API key:

api = Gravatar.new("generic@example.com", :api_key => "AbCdEfG1234")

api.exists?("another@example.com") #=> true or false, depending on whether the specified email exists.

If the user doesn't have a gravatar, an image will be generated for them based on the email (at least that has been my experience). I've used the gem gravatar_image_tag - http://rubygems.org/gems/gravatar_image_tag which lets you change the default gravatar image.

someoneinomaha
  • 1,304
  • 2
  • 14
  • 21
  • This is maybe another approach to try: http://stackoverflow.com/questions/2103620/gravatar-how-do-i-know-if-a-user-has-a-real-picture?rq=1 – someoneinomaha Jul 20 '12 at 21:54
  • well, i just did not catch the politics gem vs gravatar. As in written in gravatar documentation u can easy pass d= parameter to an image request: 404: do not load any image if none is associated with the email hash, instead return an HTTP 404 (File Not Found) response. That i was looking for in the mentioned gem – Jakub Kuchar Jul 21 '12 at 16:06
1
if (response.code.to_i == 404)
  return false
else
  return true
end

Instead of whole block, use only this(as a last line):

response.code.to_i != 404
alexey_the_cat
  • 1,812
  • 19
  • 33