From 07e4c65f6a38778750716a7b96f851becd4661ca Mon Sep 17 00:00:00 2001 From: Jason Lee Date: Tue, 20 Aug 2024 18:21:09 +0800 Subject: [PATCH 1/2] Add test to covert #87 --- crates/support/src/backend.rs | 5 +---- tests/integration_tests.rs | 10 ++++++++++ 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/crates/support/src/backend.rs b/crates/support/src/backend.rs index 54fd031..ff9c38a 100644 --- a/crates/support/src/backend.rs +++ b/crates/support/src/backend.rs @@ -74,10 +74,7 @@ impl SimpleBackend { .map(|(k, v)| ((*k).into(), (*v).into())) .collect::>(); - let trs = self - .translations - .entry(locale.into()) - .or_insert(HashMap::new()); + let trs = self.translations.entry(locale.into()).or_default(); trs.extend(data); } } diff --git a/tests/integration_tests.rs b/tests/integration_tests.rs index 9e88084..dcaa52f 100644 --- a/tests/integration_tests.rs +++ b/tests/integration_tests.rs @@ -33,6 +33,8 @@ rust_i18n::i18n!( #[cfg(test)] mod tests { + use std::{thread, time::Duration}; + use rust_i18n::t; use rust_i18n_support::load_locales; @@ -315,4 +317,12 @@ mod tests { "This is missing key fallbacked to en." ); } + + #[test] + fn test_set_locale() { + rust_i18n::set_locale("zh-CN"); + for _ in 0..5 { + assert_eq!(t!("hello"), "Bar - 你好世界!"); + } + } } From 19e91452b403f119de43ed1f198dd49057fbfa3e Mon Sep 17 00:00:00 2001 From: Jason Lee Date: Tue, 20 Aug 2024 18:40:35 +0800 Subject: [PATCH 2/2] Fix lazy init always "en" Closes #87 #88 Co-authored-by: yk0n9 Co-authored-by: KKRainbow --- crates/macro/src/lib.rs | 10 +++++++++- tests/integration_tests.rs | 2 -- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/crates/macro/src/lib.rs b/crates/macro/src/lib.rs index 49470cf..d8b2ae3 100644 --- a/crates/macro/src/lib.rs +++ b/crates/macro/src/lib.rs @@ -324,6 +324,8 @@ fn generate_code( quote! { use rust_i18n::{BackendExt, CowStr, MinifyKey}; use std::borrow::Cow; + use std::sync::Mutex; + use rust_i18n::once_cell::sync::Lazy; /// I18n backend instance /// @@ -334,11 +336,17 @@ fn generate_code( #(#all_translations)* #extend_code - #default_locale + if *_RUST_I18N_INITIALIZED_DEFAULT_LOCALE.lock().unwrap() == false { + *_RUST_I18N_INITIALIZED_DEFAULT_LOCALE.lock().unwrap() = true; + #default_locale + } Box::new(backend) }); + /// To mark the default locale has been initialized + static _RUST_I18N_INITIALIZED_DEFAULT_LOCALE: Lazy> = Lazy::new(|| Mutex::new(false)); + static _RUST_I18N_FALLBACK_LOCALE: Option<&[&'static str]> = #fallback; static _RUST_I18N_MINIFY_KEY: bool = #minify_key; static _RUST_I18N_MINIFY_KEY_LEN: usize = #minify_key_len; diff --git a/tests/integration_tests.rs b/tests/integration_tests.rs index dcaa52f..18fbd9f 100644 --- a/tests/integration_tests.rs +++ b/tests/integration_tests.rs @@ -33,8 +33,6 @@ rust_i18n::i18n!( #[cfg(test)] mod tests { - use std::{thread, time::Duration}; - use rust_i18n::t; use rust_i18n_support::load_locales;