Skip to main content

modo/i18n/
config.rs

1use serde::Deserialize;
2
3/// Configuration for the i18n module.
4///
5/// All fields have sensible defaults and can be overridden via YAML config.
6/// Paths are relative to the working directory of the running process.
7///
8/// # Defaults
9///
10/// | Field                | Default     |
11/// |----------------------|-------------|
12/// | `locales_path`       | `"locales"` |
13/// | `default_locale`     | `"en"`      |
14/// | `locale_cookie`      | `"lang"`    |
15/// | `locale_query_param` | `"lang"`    |
16#[non_exhaustive]
17#[derive(Debug, Clone, Deserialize)]
18#[serde(default)]
19pub struct I18nConfig {
20    /// Directory that contains locale subdirectories with YAML translation files.
21    pub locales_path: String,
22    /// BCP 47 language tag used when no locale can be resolved from the request.
23    pub default_locale: String,
24    /// Cookie name read by [`CookieResolver`](super::CookieResolver) to determine the active locale.
25    pub locale_cookie: String,
26    /// Query-string parameter name read by [`QueryParamResolver`](super::QueryParamResolver).
27    pub locale_query_param: String,
28}
29
30impl Default for I18nConfig {
31    fn default() -> Self {
32        Self {
33            locales_path: "locales".into(),
34            default_locale: "en".into(),
35            locale_cookie: "lang".into(),
36            locale_query_param: "lang".into(),
37        }
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44
45    #[test]
46    fn default_config_has_sensible_values() {
47        let config = I18nConfig::default();
48        assert_eq!(config.locales_path, "locales");
49        assert_eq!(config.default_locale, "en");
50        assert_eq!(config.locale_cookie, "lang");
51        assert_eq!(config.locale_query_param, "lang");
52    }
53
54    #[test]
55    fn config_deserializes_from_yaml() {
56        let yaml = r#"
57            locales_path: "i18n"
58            default_locale: "uk"
59            locale_cookie: "locale"
60            locale_query_param: "locale"
61        "#;
62        let config: I18nConfig = serde_yaml_ng::from_str(yaml).unwrap();
63        assert_eq!(config.locales_path, "i18n");
64        assert_eq!(config.default_locale, "uk");
65        assert_eq!(config.locale_cookie, "locale");
66        assert_eq!(config.locale_query_param, "locale");
67    }
68
69    #[test]
70    fn config_uses_defaults_for_missing_fields() {
71        let yaml = r#"
72            default_locale: "uk"
73        "#;
74        let config: I18nConfig = serde_yaml_ng::from_str(yaml).unwrap();
75        assert_eq!(config.default_locale, "uk");
76        assert_eq!(config.locales_path, "locales");
77        assert_eq!(config.locale_cookie, "lang");
78        assert_eq!(config.locale_query_param, "lang");
79    }
80}