Skip to content

Commit

Permalink
Fix lazy init always "en" (#90)
Browse files Browse the repository at this point in the history
Co-authored-by: yk0n9 <[email protected]>
Co-authored-by: KKRainbow <[email protected]>
  • Loading branch information
3 people authored Aug 20, 2024
1 parent 5d4b561 commit 6389570
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 5 deletions.
10 changes: 9 additions & 1 deletion crates/macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
///
Expand All @@ -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<Mutex<bool>> = 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;
Expand Down
5 changes: 1 addition & 4 deletions crates/support/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,7 @@ impl SimpleBackend {
.map(|(k, v)| ((*k).into(), (*v).into()))
.collect::<HashMap<_, _>>();

let trs = self
.translations
.entry(locale.into())
.or_insert(HashMap::new());
let trs = self.translations.entry(locale.into()).or_default();
trs.extend(data);
}
}
Expand Down
8 changes: 8 additions & 0 deletions tests/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -315,4 +315,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 - 你好世界!");
}
}
}

0 comments on commit 6389570

Please sign in to comment.