naming_conventions/conventions/
kebab_case.rs1use crate::{conventions::to_no_case, Convention};
2
3use regex::{Error, Regex};
4
5pub struct KebabCase;
6
7impl Convention for KebabCase {
8 fn to(&self, string: &str) -> Result<String, Error> {
9 to_kebab_case(string)
10 }
11
12 fn is(&self, string: &str) -> Result<bool, Error> {
13 is_kebab_case(string)
14 }
15}
16
17pub fn to_kebab_case(string: &str) -> Result<String, Error> {
18 let no_case = to_no_case(string)?.to_lowercase();
19
20 let re = Regex::new(r"\s+").unwrap();
21 let result = re.replace_all(&no_case, "-").to_string();
22
23 log::debug!(target: "convention::kebab_case::to_kebab_case", "'{}' changed to '{}' (kebab_case).", string, result);
24 Ok(result)
25}
26
27pub fn is_kebab_case(string: &str) -> Result<bool, Error> {
28 let kebab_case = to_kebab_case(string)?;
29 Ok(kebab_case == string)
30}
31
32#[cfg(test)]
33mod tests {
34 use super::*;
35
36 fn init() {
37 dotenv::dotenv().ok();
38 let _ = env_logger::try_init();
39 }
40
41 #[test]
42 fn test_to_kebab_case() {
43 tests::init();
44
45 let result = to_kebab_case("vahid_Vakili ").unwrap();
46 assert_eq!(&result, "vahid-vakili")
47 }
48
49 #[test]
50 fn test_is_kebab_case() {
51 tests::init();
52
53 let result = is_kebab_case("vahid-vakili").unwrap();
54 assert_eq!(result, true);
55
56 let result = is_kebab_case("vahid_Vakili").unwrap();
57 assert_eq!(result, false);
58 }
59}