Skip to content

Commit 67a5f46

Browse files
committed
Add FluentBundle::add_builtins()
1 parent 77eb38a commit 67a5f46

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

fluent-bundle/src/bundle.rs

+55
Original file line numberDiff line numberDiff line change
@@ -547,6 +547,61 @@ impl<R, M> FluentBundle<R, M> {
547547
}),
548548
}
549549
}
550+
551+
/// Adds the builtin functions described in the [FTL syntax guide] to the bundle, making them
552+
/// available in messages.
553+
///
554+
/// # Examples
555+
///
556+
/// ```
557+
/// use fluent_bundle::{FluentArgs, FluentBundle, FluentResource, FluentValue};
558+
/// use unic_langid::langid;
559+
///
560+
/// let ftl_string = String::from(r#"rank = { NUMBER($n, type: "ordinal") ->
561+
/// [1] first
562+
/// [2] second
563+
/// [3] third
564+
/// [one] {$n}st
565+
/// [two] {$n}nd
566+
/// [few] {$n}rd
567+
/// *[other] {$n}th
568+
/// }"#);
569+
/// let resource = FluentResource::try_new(ftl_string)
570+
/// .expect("Could not parse an FTL string.");
571+
/// let langid_en = langid!("en-US");
572+
/// let mut bundle = FluentBundle::new(vec![langid_en]);
573+
/// bundle.add_resource(&resource)
574+
/// .expect("Failed to add FTL resources to the bundle.");
575+
///
576+
/// // Register the builtin functions (including NUMBER())
577+
/// bundle.add_builtins().expect("Failed to add builtins to the bundle.");
578+
///
579+
/// let msg = bundle.get_message("rank").expect("Message doesn't exist.");
580+
/// let mut errors = vec![];
581+
/// let pattern = msg.value().expect("Message has no value.");
582+
///
583+
/// let mut args = FluentArgs::new();
584+
///
585+
/// args.set("n", 5);
586+
/// let value = bundle.format_pattern(&pattern, Some(&args), &mut errors);
587+
/// assert_eq!(&value, "\u{2068}5\u{2069}th");
588+
///
589+
/// args.set("n", 12);
590+
/// let value = bundle.format_pattern(&pattern, Some(&args), &mut errors);
591+
/// assert_eq!(&value, "\u{2068}12\u{2069}th");
592+
///
593+
/// args.set("n", 22);
594+
/// let value = bundle.format_pattern(&pattern, Some(&args), &mut errors);
595+
/// assert_eq!(&value, "\u{2068}22\u{2069}nd");
596+
/// ```
597+
///
598+
/// [FTL syntax guide]: https://projectfluent.org/fluent/guide/functions.html
599+
pub fn add_builtins(&mut self) -> Result<(), FluentError> {
600+
self.add_function("NUMBER", crate::builtins::NUMBER)?;
601+
// TODO: DATETIME()
602+
603+
Ok(())
604+
}
550605
}
551606

552607
impl<R> Default for FluentBundle<R, IntlLangMemoizer> {

0 commit comments

Comments
 (0)