Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix lazy init always "en" #90

Merged
merged 2 commits into from
Aug 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 - 你好世界!");
}
}
}
Loading