Skip to content

Commit ad02a92

Browse files
add docs to ArgumentResolver and the type-safe messages example
1 parent 5510baa commit ad02a92

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

fluent-bundle/examples/typesafe_messages.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,13 @@
1+
// This is an example of an application which adds a custom argument resolver
2+
// to add type safety.
3+
// See the external_arguments example if you are not yet familiar with fluent arguments.
4+
//
5+
// The goal is that we prevent bugs caused by mixing up arguments that belong
6+
// to different messages.
7+
// We can achieve this by defining structs for each message that encode the
8+
// argument types with the corresponding message ID, and then hooking into
9+
// fluent's resolver using a custom fluent_bundle::ArgumentResolver implementation.
10+
111
use std::borrow::Cow;
212

313
use fluent_bundle::{ArgumentResolver, FluentBundle, FluentError, FluentResource, FluentValue};
@@ -98,13 +108,16 @@ trait Message<'a> {
98108
fn get_arg(&self, name: &str) -> Option<FluentValue<'a>>;
99109
}
100110

111+
// by using &dyn, we prevent monomorphization for each Message struct
112+
// this keeps binary code size in check
101113
impl<'a, 'b> ArgumentResolver<'a> for &'a dyn Message<'b> {
102114
fn resolve(self, name: &str) -> Option<Cow<FluentValue<'a>>> {
103115
let arg = self.get_arg(name)?;
104116
Some(Cow::Owned(arg))
105117
}
106118
}
107119

120+
// allows for method syntax, i.e. bundle.format_message(...)
108121
trait CustomizedBundle {
109122
fn format_message<'b>(
110123
&'b self,

fluent-bundle/src/resolver/scope.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,11 @@ impl<'bundle, 'ast, 'args, 'errors, R, M, Args: ArgumentResolver<'args>>
146146
}
147147
}
148148

149+
/// Determines how to retrieve argument values when resolving fluent messages.
150+
/// This trait can be used to implement an alternative to [`FluentArgs`].
151+
///
152+
/// One example usage is for argument type safety that [`FluentArgs`] can't provide due to its
153+
/// flexible nature. See `fluent-bundle/examples/typesafe_messages.rs` for an example of this.
149154
pub trait ArgumentResolver<'a>: Copy {
150155
fn resolve(self, name: &str) -> Option<Cow<FluentValue<'a>>>;
151156
}

0 commit comments

Comments
 (0)