class Libravatar
Attributes
default[RW]
email[RW]
https[RW]
openid[RW]
size[RW]
Public Class Methods
new(options = {})
click to toggle source
The options should contain :email or :openid values. If both are given, email will be used. The value of openid and email will be normalized by the rule described in www.libravatar.org/api
List of option keys:
-
:email
-
:openid
-
:size An integer ranged 1 - 512, default is 80.
-
:https Set to true to serve avatars over SSL
-
:default URL to redirect missing avatars to, or one of these specials: “404”, “mm”, “identicon”, “monsterid”, “wavatar”, “retro”
# File lib/libravatar.rb, line 33 def initialize(options = {}) @email = options[:email] @openid = options[:openid] @size = options[:size] @default = options[:default] @https = options[:https] end
Public Instance Methods
get_base_url()
click to toggle source
# File lib/libravatar.rb, line 79 def get_base_url profile = @@profiles[ @https ? 1 : 0 ] target, port = srv_lookup if (target && port) port_fragment = port != profile[:port] ? ':' + port.to_s : '' return profile[:scheme] + target.to_s + port_fragment else return profile[:scheme] + profile[:host] end end
get_target_domain()
click to toggle source
# File lib/libravatar.rb, line 41 def get_target_domain return @email.split('@')[1] if @email return URI.parse(@openid).host end
srv_lookup()
click to toggle source
Grab the DNS SRV records associated with the target domain, and choose one according to RFC2782.
# File lib/libravatar.rb, line 60 def srv_lookup profile = @@profiles[ @https ? 1 : 0 ] Resolv::DNS::open do |dns| rrs = dns.getresources(profile[:srv] + get_target_domain(), Resolv::DNS::Resource::IN::SRV).to_a return [nil, nil] unless rrs.any? min_priority = rrs.map{ |r| r.priority }.min rrs.delete_if{ |r| r.priority != min_priority } weight_sum = rrs.inject(0) { |a,r| a+r.weight }.to_f r = rrs.max_by { |r| r.weight == 0 ? 0 : rand ** (weight_sum / r.weight) } return [r.target, r.port] end end
to_s()
click to toggle source
Generate the libravatar URL
# File lib/libravatar.rb, line 92 def to_s if @email @email.downcase! id = Digest::MD5.hexdigest(@email) else id = Digest::SHA2.hexdigest(normalize_openid(@openid)) end s = @size ? "s=#{@size}" : nil d = @default ? "d=#{@default}" : nil query = [s,d].reject{|x|!x}.join("&") query = "?#{query}" unless query == "" baseurl = get_base_url() + '/avatar/' return baseurl + id + query end
Private Instance Methods
normalize_openid(s)
click to toggle source
Normalize an openid URL following the description on libravatar.org
# File lib/libravatar.rb, line 119 def normalize_openid(s) x = URI.parse(s) x.host.downcase! x.scheme = x.scheme.downcase if (x.path == "" && x.fragment == nil) x.path = "/" end return x.to_s end
sanitize_srv_lookup(hostname, port)
click to toggle source
# File lib/libravatar.rb, line 110 def sanitize_srv_lookup(hostname, port) unless hostname.match(/^[0-9a-zA-Z\-.]+$/) && 1 <= port && port <= 65535 return [nil, nil] end return [hostname, port] end