#[derive(Debug, Clone)]
pub struct LangConfig {
pub locale: String,
pub fallback_locale: String,
pub path: String,
}
impl LangConfig {
pub fn from_env() -> Self {
Self {
locale: std::env::var("APP_LOCALE").unwrap_or_else(|_| "en".to_string()),
fallback_locale: std::env::var("APP_FALLBACK_LOCALE")
.unwrap_or_else(|_| "en".to_string()),
path: std::env::var("LANG_PATH").unwrap_or_else(|_| "lang".to_string()),
}
}
pub fn builder() -> LangConfigBuilder {
LangConfigBuilder::default()
}
}
impl Default for LangConfig {
fn default() -> Self {
Self::from_env()
}
}
#[derive(Default)]
pub struct LangConfigBuilder {
locale: Option<String>,
fallback_locale: Option<String>,
path: Option<String>,
}
impl LangConfigBuilder {
pub fn locale(mut self, locale: impl Into<String>) -> Self {
self.locale = Some(locale.into());
self
}
pub fn fallback_locale(mut self, fallback: impl Into<String>) -> Self {
self.fallback_locale = Some(fallback.into());
self
}
pub fn path(mut self, path: impl Into<String>) -> Self {
self.path = Some(path.into());
self
}
pub fn build(self) -> LangConfig {
let default = LangConfig::from_env();
LangConfig {
locale: self.locale.unwrap_or(default.locale),
fallback_locale: self.fallback_locale.unwrap_or(default.fallback_locale),
path: self.path.unwrap_or(default.path),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn from_env_and_defaults() {
std::env::remove_var("APP_LOCALE");
std::env::remove_var("APP_FALLBACK_LOCALE");
std::env::remove_var("LANG_PATH");
let config = LangConfig::from_env();
assert_eq!(config.locale, "en");
assert_eq!(config.fallback_locale, "en");
assert_eq!(config.path, "lang");
std::env::set_var("APP_LOCALE", "es");
std::env::set_var("APP_FALLBACK_LOCALE", "fr");
std::env::set_var("LANG_PATH", "resources/lang");
let config = LangConfig::from_env();
assert_eq!(config.locale, "es");
assert_eq!(config.fallback_locale, "fr");
assert_eq!(config.path, "resources/lang");
let config = LangConfig::default();
assert_eq!(config.locale, "es");
std::env::remove_var("APP_LOCALE");
std::env::remove_var("APP_FALLBACK_LOCALE");
std::env::remove_var("LANG_PATH");
}
#[test]
fn builder_overrides_fields() {
let config = LangConfig::builder()
.locale("pt-br")
.fallback_locale("en")
.path("translations")
.build();
assert_eq!(config.locale, "pt-br");
assert_eq!(config.fallback_locale, "en");
assert_eq!(config.path, "translations");
}
#[test]
fn builder_fills_unset_from_defaults() {
let config = LangConfig::builder().locale("de").build();
assert_eq!(config.locale, "de");
}
}