use super::bundle::{I18nBundle, Locale};
pub fn t(locale: &Locale, bundle: &I18nBundle, key: &str) -> String {
bundle.translate(locale, key)
}
pub fn t_with_args(
locale: &Locale,
bundle: &I18nBundle,
key: &str,
args: &[(&str, String)],
) -> String {
bundle.translate_with_args(locale, key, args)
}
pub fn tr_log(key: &str) -> String {
match super::startup_i18n() {
Some((locale, bundle)) => t(locale, bundle, key),
None => key.to_string(),
}
}
pub fn tr_log_args(key: &str, args: &[(&str, String)]) -> String {
match super::startup_i18n() {
Some((locale, bundle)) => t_with_args(locale, bundle, key, args),
None => key.to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn test_bundle() -> I18nBundle {
I18nBundle::load("en-US", &["en-US", "zh-CN"]).unwrap()
}
#[test]
fn test_t_function() {
let bundle = test_bundle();
let locale: Locale = "en-US".parse().unwrap();
let msg = t(&locale, &bundle, "error-permission");
assert_eq!(msg, "Permission denied.");
}
#[test]
fn test_t_with_args_function() {
let bundle = test_bundle();
let locale: Locale = "en-US".parse().unwrap();
let msg = t_with_args(
&locale,
&bundle,
"error-validation",
&[("message", "invalid input".to_string())],
);
assert_eq!(msg, "Validation error: invalid input");
}
#[test]
fn test_t_zh_cn() {
let bundle = test_bundle();
let locale: Locale = "zh-CN".parse().unwrap();
let msg = t(&locale, &bundle, "error-permission");
assert_eq!(msg, "权限不足。");
}
}