Skip to content

Commit

Permalink
Improve t! macro for supports expr with arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
huacnlee committed Dec 9, 2021
1 parent 24e3d98 commit a6072c7
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,12 +107,12 @@ macro_rules! t {
};

// t!("foo", locale="en")
($key:expr, locale=$locale:tt) => {
($key:expr, locale=$locale:expr) => {
crate::translate($locale, $key)
};

// t!("foo", locale="en")
($key:expr, locale=$locale:tt, $($var_name:tt = $var_val:tt),+) => {
($key:expr, locale=$locale:expr, $($var_name:tt = $var_val:expr),+) => {
{
let mut message = crate::translate($locale, $key);
$(
Expand All @@ -123,7 +123,7 @@ macro_rules! t {
};

// t!("foo {} {}", "bar", "baz")
($key:expr, $($var_name:tt = $var_val:tt),+) => {
($key:expr, $($var_name:tt = $var_val:expr),+) => {
{
let mut message = crate::translate(rust_i18n::locale().as_str(), $key);
$(
Expand Down
39 changes: 39 additions & 0 deletions tests/intergartion_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ mod tests {
t!("messages.hello", locale = "en", name = "Jason"),
"Hello, Jason!"
);
assert_eq!(
t!("messages.hello", name = "Jason", locale = "en"),
"Hello, Jason!"
);
assert_eq!(
t!("messages.hello", locale = "de", name = "Jason"),
"Hallo, Jason!"
Expand All @@ -57,4 +61,39 @@ mod tests {
assert_eq!(t!("user.title"), "User Title");
assert_eq!(t!("messages.user.title"), "Message User Title");
}

#[test]
fn it_support_expr() {
rust_i18n::set_locale("en");
let name = "Jason Lee";
let locale = "en";

let key = "messages.hello";

assert_eq!(
t!(&format!("messages.{}", "hello"), name = name),
"Hello, Jason Lee!"
);
assert_eq!(t!(key, name = name), "Hello, Jason Lee!");

assert_eq!(
t!("messages.hello", name = &name.to_string()),
"Hello, Jason Lee!"
);
assert_eq!(
t!("messages.hello", name = &format!("this is {}", name)),
"Hello, this is Jason Lee!"
);

assert_eq!(t!("messages.hello", locale = locale), "Hello, %{name}!");

assert_eq!(
t!("messages.hello", name = name, locale = locale),
"Hello, Jason Lee!"
);
assert_eq!(
t!("messages.hello", name = name, locale = &locale.to_string()),
"Hello, Jason Lee!"
);
}
}

0 comments on commit a6072c7

Please sign in to comment.