Created
October 9, 2013 10:36
-
-
Save adammcarth/6899302 to your computer and use it in GitHub Desktop.
Validating and saving a Gravatar URL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AvatarValidator < ActiveModel::Validator | |
def validate(record) | |
unless gravatar_exists? | |
return record.errors[:avatar] << "No display picture could be found on Gravatar using #{record.avatar}." | |
end | |
end | |
end | |
class Comment < ActiveRecord::Base | |
has_one :post | |
include ActiveModel::Validations | |
validates_with AvatarValidator | |
after_validation :save_avatar_link | |
end | |
private | |
require "digest/md5" | |
require "net/http" | |
def gravatar_exists? | |
hashed_email = Digest::MD5.hexdigest(self.avatar) | |
gravatar_check = "http://gravatar.com/avatar/#{hashed_email}.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 | |
def save_avatar_link | |
if gravatar_exists? | |
hashed_email = Digest::MD5.hexdigest(self.avatar.downcase) | |
self.avatar = "http://gravatar.com/avatar/#{hashed_email}.png" | |
else | |
self.avatar = "/assets/default_avatar.jpg" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment