1#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct Names {
10 pub model: String,
12 pub snake: String,
14 pub plural: String,
16 pub controller: String,
18 pub controller_file: String,
20 pub store_request: String,
22 pub update_request: String,
24 pub policy: String,
26 pub factory: String,
28 pub seeder: String,
30}
31
32impl Names {
33 pub fn new(input: &str) -> Self {
36 let snake = to_snake(input);
37 let model = to_pascal(&snake);
38 let plural = pluralize(&snake);
39
40 Self {
41 controller: format!("{}Controller", to_pascal(&plural)),
42 controller_file: format!("{plural}_controller"),
43 store_request: format!("Store{model}"),
44 update_request: format!("Update{model}"),
45 policy: format!("{model}Policy"),
46 factory: format!("{model}Factory"),
47 seeder: format!("{model}Seeder"),
48 model,
49 snake,
50 plural,
51 }
52 }
53}
54
55pub fn to_snake(input: &str) -> String {
57 let mut out = String::with_capacity(input.len() + 4);
58 let mut previous_lower = false;
59
60 for ch in input.chars() {
61 if ch == '_' || ch == '-' || ch == ' ' {
62 if !out.ends_with('_') && !out.is_empty() {
63 out.push('_');
64 }
65 previous_lower = false;
66 continue;
67 }
68
69 if ch.is_uppercase() {
70 if previous_lower && !out.is_empty() {
71 out.push('_');
72 }
73 out.extend(ch.to_lowercase());
74 previous_lower = false;
75 } else {
76 out.push(ch);
77 previous_lower = true;
78 }
79 }
80
81 out
82}
83
84pub fn to_pascal(input: &str) -> String {
86 input
87 .split('_')
88 .filter(|part| !part.is_empty())
89 .map(|part| {
90 let mut chars = part.chars();
91 match chars.next() {
92 Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
93 None => String::new(),
94 }
95 })
96 .collect()
97}
98
99pub fn pluralize(input: &str) -> String {
102 let (head, last) = match input.rsplit_once('_') {
103 Some((head, last)) => (Some(head), last),
104 None => (None, input),
105 };
106
107 let plural = if last.is_empty() {
108 String::new()
109 } else if let Some(stem) = last.strip_suffix('y') {
110 if stem.chars().last().is_some_and(is_vowel) {
112 format!("{last}s")
113 } else {
114 format!("{stem}ies")
115 }
116 } else if last.ends_with('s')
117 || last.ends_with("sh")
118 || last.ends_with("ch")
119 || last.ends_with('x')
120 || last.ends_with('z')
121 {
122 format!("{last}es")
123 } else {
124 format!("{last}s")
125 };
126
127 match head {
128 Some(head) => format!("{head}_{plural}"),
129 None => plural,
130 }
131}
132
133fn is_vowel(ch: char) -> bool {
134 matches!(ch, 'a' | 'e' | 'i' | 'o' | 'u')
135}
136
137#[cfg(test)]
138mod tests {
139 use super::*;
140
141 #[test]
142 fn snake_cases_every_spelling() {
143 assert_eq!(to_snake("User"), "user");
144 assert_eq!(to_snake("UserProfile"), "user_profile");
145 assert_eq!(to_snake("user_profile"), "user_profile");
146 assert_eq!(to_snake("userProfile"), "user_profile");
147 assert_eq!(to_snake("user-profile"), "user_profile");
148 }
149
150 #[test]
151 fn pascal_cases_from_snake() {
152 assert_eq!(to_pascal("user"), "User");
153 assert_eq!(to_pascal("user_profile"), "UserProfile");
154 }
155
156 #[test]
157 fn pluralizes_the_common_shapes() {
158 assert_eq!(pluralize("user"), "users");
159 assert_eq!(pluralize("post"), "posts");
160 assert_eq!(pluralize("category"), "categories");
161 assert_eq!(
162 pluralize("day"),
163 "days",
164 "a vowel before `y` just takes `s`"
165 );
166 assert_eq!(pluralize("address"), "addresses");
167 assert_eq!(pluralize("branch"), "branches");
168 assert_eq!(pluralize("box"), "boxes");
169 assert_eq!(pluralize("user_profile"), "user_profiles");
170 }
171
172 #[test]
173 fn round_trips_against_the_derive_singularizer() {
174 for word in [
177 "users",
178 "posts",
179 "categories",
180 "addresses",
181 "branches",
182 "user_profiles",
183 ] {
184 let singular = crate::naming::tests::singularize_like_derive(word);
185 assert_eq!(pluralize(&singular), word, "round trip failed for {word}");
186 }
187 }
188
189 fn singularize_like_derive(table: &str) -> String {
191 let (head, last) = match table.rsplit_once('_') {
192 Some((head, last)) => (Some(head), last),
193 None => (None, table),
194 };
195
196 let singular = if let Some(stem) = last.strip_suffix("ies") {
197 format!("{stem}y")
198 } else if last.ends_with("sses") || last.ends_with("shes") || last.ends_with("ches") {
199 last.trim_end_matches("es").to_owned()
200 } else if last.ends_with("ss") {
201 last.to_owned()
202 } else if let Some(stem) = last.strip_suffix('s') {
203 stem.to_owned()
204 } else {
205 last.to_owned()
206 };
207
208 match head {
209 Some(head) => format!("{head}_{singular}"),
210 None => singular,
211 }
212 }
213
214 #[test]
215 fn derives_every_name_from_one_input() {
216 let names = Names::new("UserProfile");
217
218 assert_eq!(names.model, "UserProfile");
219 assert_eq!(names.snake, "user_profile");
220 assert_eq!(names.plural, "user_profiles");
221 assert_eq!(names.controller, "UserProfilesController");
222 assert_eq!(names.controller_file, "user_profiles_controller");
223 assert_eq!(names.store_request, "StoreUserProfile");
224 assert_eq!(names.update_request, "UpdateUserProfile");
225 assert_eq!(names.policy, "UserProfilePolicy");
226 }
227
228 #[test]
229 fn normalises_however_the_user_typed_it() {
230 assert_eq!(Names::new("user"), Names::new("User"));
231 assert_eq!(Names::new("user_profile"), Names::new("UserProfile"));
232 }
233}