Skip to content

Instantly share code, notes, and snippets.

@adammcarth
Created October 9, 2013 10:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adammcarth/6899302 to your computer and use it in GitHub Desktop.
Save adammcarth/6899302 to your computer and use it in GitHub Desktop.
Validating and saving a Gravatar URL
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