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

Allow optional arguments #273

Merged
merged 3 commits into from
Oct 27, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 12 additions & 0 deletions fluent-bundle/src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,3 +206,15 @@ impl<'source> From<Cow<'source, str>> for FluentValue<'source> {
FluentValue::String(s)
}
}

impl<'source, T> From<Option<T>> for FluentValue<'source>
where
T: Into<FluentValue<'source>>,
{
fn from(v: Option<T>) -> Self {
match v {
Some(v) => v.into(),
None => FluentValue::None,
}
}
}
58 changes: 58 additions & 0 deletions fluent-bundle/tests/optional_value.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
use fluent_bundle::{FluentArgs, FluentBundle, FluentResource};

#[test]
fn test_optional_value() {
let ftl_string = String::from(
"
hello = { $title ->
[Miss] Hello, Miss. { $name }!
[Mr] Hello, Mr. { $name }!
[Mrs] Hello, Mrs. { $name }!
[Ms] Hello, Ms. { $name }!
*[Mx] Hello, Mx. { $name }!
}
",
);

let res = FluentResource::try_new(ftl_string).expect("Could not parse an FTL string.");
let mut bundle = FluentBundle::default();
bundle.set_use_isolating(false);

bundle
.add_resource(res)
.expect("Failed to add FTL resources to the bundle.");

let msg = bundle.get_message("hello").expect("Message doesn't exist.");

let pattern = msg.value().expect("Message has no value.");

// Optional value that matches a non-default variant
let mut args = FluentArgs::new();
let title = Some("Mr");
args.set("title", title);
args.set("name", "John");

let mut errors = vec![];
let value = bundle.format_pattern(pattern, Some(&args), &mut errors);
assert_eq!("Hello, Mr. John!", &value);

// No value, use default variant
let mut args = FluentArgs::new();
let title: Option<&str> = None;
args.set("title", title);
args.set("name", "John");

let mut errors = vec![];
let value = bundle.format_pattern(pattern, Some(&args), &mut errors);
assert_eq!("Hello, Mx. John!", &value);

// Optional value that does not match any variant and therefore reverts to the default variant
let mut args = FluentArgs::new();
let title = Some(2);
args.set("title", title);
args.set("name", "John");

let mut errors = vec![];
let value = bundle.format_pattern(pattern, Some(&args), &mut errors);
assert_eq!("Hello, Mx. John!", &value);
}