Skip to content

Commit

Permalink
Use HEAD instead of GET for gravatar image check. Add simple tests fo…
Browse files Browse the repository at this point in the history
…r Author.
  • Loading branch information
james cook committed Mar 25, 2011
1 parent 59bb47c commit 91450c7
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 15 deletions.
47 changes: 32 additions & 15 deletions models/author.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ def self.create_from_hash!(hsh)
)
end

def self.gravatar_host
"gravatar.com"
end

def url
if remote_url.nil?
"/users/#{username}"
Expand All @@ -34,26 +38,39 @@ def url
end

def avatar_url
if image_url.nil?
if email.nil?
# Using a default avatar
"/images/avatar.png"
return image_url if image_url

if email
valid_gravatar? ? gravatar_url : "/images/avatar.png"
else
# Using a default avatar
"/images/avatar.png"
end
end

def valid_gravatar?
return false unless use_gravatar?
uri = URI.parse(gravatar_url)
result = Net::HTTP.start(Author.gravatar_host, 80) do |http|
res = http.head(uri.path + "?" + uri.query ) # Use HEAD instead of GET for a faster response

if res.class == Net::HTTPNotFound
return false
else
# Using gravatar
current_url = "http://gravatar.com/avatar/" + Digest::MD5.hexdigest(email) + "?s=48&r=r&d=404"
res = Net::HTTP.get_response(URI.parse(current_url))
if res.class == Net::HTTPNotFound
"/images/avatar.png"
else
current_url
end
return true
end
else
# Use the twitter image
image_url
end
end

def gravatar_url
path = "/avatar/" + Digest::MD5.hexdigest(email) + "?s=48&r=r&d=404"
["http://", Author.gravatar_host, path].join ""
end

private
def use_gravatar?
@use_gravatar || false # Useful for tests
end
end


30 changes: 30 additions & 0 deletions test/author_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
require_relative "test_helper"

class AuthorTest < MiniTest::Unit::TestCase

include TestHelper
def setup
@author = Factory.build :author, :username => "james", :email => nil, :image_url => nil
@author.instance_variable_set "@use_gravatar", true
end

def test_create_from_hash
hash = {"user_info" => {"name" => "james", "nickname" => "jim", "urls" => {}} }
assert Author.create_from_hash!(hash).is_a?(Author)
end

def test_url
@author.remote_url = "some_url.com"
assert_equal @author.url, @author.remote_url
end

def test_valid_avatar_url
@author.email = "[email protected]"
assert_equal @author.avatar_url, @author.gravatar_url
end

def test_invalid_avatar_url
@author.email = "[email protected]"
assert_equal @author.avatar_url, "/images/avatar.png"
end
end

0 comments on commit 91450c7

Please sign in to comment.