use std::collections::HashSet;
use regex::Regex;
use ruby_inflector::case::{
to_case_camel_like, to_class_case as to_class_case_original, CamelOptions,
};
pub fn to_class_case(
s: &str,
should_singularize: bool,
acronyms: &HashSet<String>,
) -> String {
let options = CamelOptions {
new_word: true,
last_char: ' ',
first_word: false,
injectable_char: ' ',
has_seperator: false,
inverted: false,
};
let mut class_name = if should_singularize {
to_class_case_original(s, acronyms)
} else {
to_case_camel_like(s, options, acronyms)
};
if class_name.contains("Statu") {
let re = Regex::new("Statuse$").unwrap();
class_name = re.replace_all(&class_name, "Status").to_string();
let re = Regex::new("Statu$").unwrap();
class_name = re.replace_all(&class_name, "Status").to_string();
let re = Regex::new("Statuss").unwrap();
re.replace_all(&class_name, "Status").to_string();
}
if class_name.contains("Daum") {
let re = Regex::new("Daum").unwrap();
class_name = re.replace_all(&class_name, "Datum").to_string();
}
if class_name.contains("Lefe") {
let re = Regex::new("Lefe").unwrap();
class_name = re.replace_all(&class_name, "Leave").to_string();
}
if class_name.contains("Leafe") {
let re = Regex::new("Leafe").unwrap();
class_name = re.replace_all(&class_name, "Leave").to_string();
}
class_name
}
pub fn camelize(s: &str, acronyms: &HashSet<String>) -> String {
let lowercase_acronyms = acronyms
.iter()
.map(|acronym| acronym.to_lowercase())
.collect::<HashSet<String>>();
let mut new_string = s.to_string();
let re = Regex::new("^[a-z\\d]*").unwrap();
new_string = re
.replace(&new_string, |caps: ®ex::Captures| {
let word = caps.get(0).unwrap().as_str();
if lowercase_acronyms.contains(word) {
word.to_uppercase()
} else {
capitalize(word)
}
})
.to_mut()
.to_string();
let re = Regex::new("(?:_|(/))([a-z\\d]*)").unwrap();
new_string = re
.replace_all(&new_string, |caps: ®ex::Captures| {
let matched_slash = caps.get(1);
let word = caps.get(2).unwrap().as_str();
let capitalized_word = if lowercase_acronyms.contains(word) {
word.to_uppercase()
} else {
capitalize(word)
};
if matched_slash.is_some() {
format!("::{}", capitalized_word)
} else {
capitalized_word
}
})
.to_mut()
.to_string();
new_string
}
fn capitalize(s: &str) -> String {
let mut c = s.chars();
match c.next() {
None => String::new(),
Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_trivial() {
let actual = to_class_case("my_string", false, &HashSet::new());
let expected = "MyString";
assert_eq!(expected, actual);
}
#[test]
fn test_digits() {
let actual =
to_class_case("my_string_401k_thing", false, &HashSet::new());
let expected = "MyString401kThing";
assert_eq!(expected, actual);
}
}