|
1 | 1 | const BASE_URL: &str = "https://gravatar.com/";
|
| 2 | + |
| 3 | +use url::Url; |
| 4 | + |
| 5 | +use crate::common::email_hash; |
| 6 | + |
| 7 | +mod format; |
| 8 | + |
| 9 | +pub use format::Format; |
| 10 | + |
| 11 | +/// Representation of a single Gravatar profile URL. |
| 12 | +#[derive(Clone, Debug)] |
| 13 | +pub struct Profile { |
| 14 | + email: String, |
| 15 | +} |
| 16 | + |
| 17 | +impl Profile { |
| 18 | + pub fn builder(email: &str) -> ProfileBuilder { |
| 19 | + ProfileBuilder::new(email) |
| 20 | + } |
| 21 | + |
| 22 | + /// Returns the URL of the Gravatar image. |
| 23 | + pub fn profile_url(self: &Self, format: Format) -> Url { |
| 24 | + let str = format!( |
| 25 | + "{}{}.{}", |
| 26 | + BASE_URL, |
| 27 | + email_hash(&self.email), |
| 28 | + format.to_string() |
| 29 | + ); |
| 30 | + Url::parse(&str).unwrap() |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +// Builder for Profile instances. |
| 35 | +#[derive(core::default::Default)] |
| 36 | +pub struct ProfileBuilder { |
| 37 | + email: String, |
| 38 | +} |
| 39 | + |
| 40 | +impl ProfileBuilder { |
| 41 | + pub fn new(email: &str) -> ProfileBuilder { |
| 42 | + ProfileBuilder { |
| 43 | + email: email.to_string(), |
| 44 | + ..core::default::Default::default() |
| 45 | + } |
| 46 | + } |
| 47 | + /// Builds the Profile instance. |
| 48 | + pub fn build(self) -> Profile { |
| 49 | + Profile { email: self.email } |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +#[cfg(test)] |
| 54 | +mod tests { |
| 55 | + use super::*; |
| 56 | + |
| 57 | + #[test] |
| 58 | + fn test_profile_builder() { |
| 59 | + |
| 60 | + |
| 61 | + let builder = Profile::builder(email); |
| 62 | + let profile = builder.build(); |
| 63 | + assert_eq!(email, profile.email); |
| 64 | + assert_eq!("https://gravatar.com/f807b5609eae64257bf4877652ea49fee40ac2451c152c12fa596ffeda647157.json", profile.profile_url(Format::Json).to_string()); |
| 65 | + assert_eq!("https://gravatar.com/f807b5609eae64257bf4877652ea49fee40ac2451c152c12fa596ffeda647157.xml", profile.profile_url(Format::Xml).to_string()); |
| 66 | + assert_eq!("https://gravatar.com/f807b5609eae64257bf4877652ea49fee40ac2451c152c12fa596ffeda647157.php", profile.profile_url(Format::Php).to_string()); |
| 67 | + assert_eq!("https://gravatar.com/f807b5609eae64257bf4877652ea49fee40ac2451c152c12fa596ffeda647157.vcf", profile.profile_url(Format::Vcard).to_string()); |
| 68 | + assert_eq!("https://gravatar.com/f807b5609eae64257bf4877652ea49fee40ac2451c152c12fa596ffeda647157.qr", profile.profile_url(Format::QrCode).to_string()); |
| 69 | + } |
| 70 | +} |
0 commit comments