How should i check if gravatar exist?
-
22-06-2021 - |
سؤال
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
المحلول
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.
نصائح أخرى
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
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