rustlings/src/url_replacer.rs

67 lines
1.5 KiB
Rust
Raw Normal View History

2024-12-07 13:01:18 +00:00
pub struct UrlReplacer {
base_url: String
2024-12-07 12:40:18 +00:00
}
const EN_BASE_URL: &str = "https://doc.rust-lang.org/book";
2024-12-07 13:01:18 +00:00
impl UrlReplacer {
/// this fn will trim url end with '/'
pub fn new(base_url: &String) -> Self {
let url = if base_url.ends_with('/') {
2024-12-08 02:19:51 +00:00
base_url.trim_end_matches('/').to_owned()
} else {
base_url.clone()
2024-12-08 02:19:51 +00:00
};
2024-12-07 12:40:18 +00:00
Self {
base_url: url
2024-12-07 12:40:18 +00:00
}
}
/// replace rustbook url
2024-12-07 12:40:18 +00:00
pub fn replace(&self, hint: &str) -> String {
2024-12-07 13:01:18 +00:00
hint.replace(EN_BASE_URL, &self.base_url)
2024-12-07 12:40:18 +00:00
}
}
2024-12-08 02:12:43 +00:00
#[cfg(test)]
mod test {
use super::*;
const TEST_DOMAIN: &str = "https://doc.rust-kr.org";
#[test]
2024-12-08 02:16:02 +00:00
fn non_rustbook_url() {
let replacer = UrlReplacer::new(&String::from(TEST_DOMAIN));
2024-12-08 02:12:43 +00:00
let hint = "\
hints (...) lines (...)
2024-12-08 02:16:02 +00:00
link: https://example.com/ch03-02-data-types.html";
2024-12-08 02:12:43 +00:00
2024-12-08 02:16:02 +00:00
assert_eq!(hint, replacer.replace(hint));
2024-12-08 02:12:43 +00:00
}
#[test]
2024-12-08 02:16:02 +00:00
fn replace_rustbook_url() {
let replacer = UrlReplacer::new(&String::from(TEST_DOMAIN));
2024-12-08 02:12:43 +00:00
let hint = "\
hints (...) lines (...)
link: https://doc.rust-lang.org/book/ch03-02-data-types.html";
assert_eq!("\
hints (...) lines (...)
link: https://doc.rust-kr.org/ch03-02-data-types.html", replacer.replace(hint));
}
2024-12-08 02:19:51 +00:00
#[test]
fn trim_end_with_slash() {
let mut domain = String::from(TEST_DOMAIN);
domain.push('/');
let replacer = UrlReplacer::new(&domain);
2024-12-08 02:19:51 +00:00
assert_eq!(TEST_DOMAIN, replacer.base_url);
}
2024-12-08 02:12:43 +00:00
}