I'm currently using mdeering's gravatar_image_tag plugin to get gravatar images for users but my dilemma is to try to detect in the code if the user has a gravatar:
If he does then display the gravatar image. If not, then display a local default image file on my server.
I'm open to using other p开发者_开发知识库lugins if they offer this functionality.
Please provide code examples. They help me learn the best.
Thanks!
You don't need gems/plugins. This screencast explains what you need step-by-step. It comes down to using the following helper method:
def avatar_url(user)
default_url = "#{root_url}images/guest.png"
gravatar_id = Digest::MD5.hexdigest(user.email.downcase)
"http://gravatar.com/avatar/#{gravatar_id}.png?s=48&d=#{CGI.escape(default_url)}"
end
Here is a helper method to check if a user has already a gravatar image :
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.
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)
if (response.code.to_i == 404)
return false
else
return true
end
end
Gravtastic gem should come to your rescue. Its fairly straightforward - you may peruse through its README. The Gem's github link
Looks like I'm extremely late to the party but the gravatar_image_tag gems does have the options that you need to accomplish this very easily.
You can configure your default image globally in your application like so:
# config/initializers/gravatar_image_tag.rb
GravatarImageTag.configure do |config|
# Set this to use your own default gravatar image rather then serving up Gravatar's default image [ 'http://example.com/images/default_gravitar.jpg', :identicon, :monsterid, :wavatar, 404 ].
config.default_image = nil
end
Or on a one off basis like so:
gravatar_image_tag('junk', alt: 'Github Default Gravatar', gravatar: { default: 'https://assets.github.com/images/gravatars/gravatar-140.png' })
精彩评论