tera_rand/
uuid.rs

1use std::collections::HashMap;
2use tera::{to_value, Result, Value};
3use uuid::Uuid;
4
5/// A Tera function to generate a random UUIDv4.
6///
7/// # Example usage
8///
9/// ```edition2021
10/// use tera::{Context, Tera};
11/// use tera_rand::random_uuid;
12///
13/// let mut tera: Tera = Tera::default();
14/// tera.register_function("random_uuid", random_uuid);
15///
16/// let context: Context = Context::new();
17/// let rendered: String = tera.render_str("{{ random_uuid() }}", &context).unwrap();
18/// ```
19#[cfg(feature = "uuid")]
20pub fn random_uuid(_args: &HashMap<String, Value>) -> Result<Value> {
21    let random_uuid: Uuid = Uuid::new_v4();
22    let json_value: Value = to_value(random_uuid.to_string())?;
23    Ok(json_value)
24}
25
26#[cfg(test)]
27mod tests {
28    use crate::common::tests::test_tera_rand_function;
29    use crate::uuid::*;
30    use tracing_test::traced_test;
31
32    #[test]
33    #[traced_test]
34    #[cfg(feature = "uuid")]
35    fn test_random_uuid() {
36        test_tera_rand_function(
37            random_uuid,
38            "random_uuid",
39            r#"{ "some_field": "{{ random_uuid() }}" }"#,
40            r#"\{ "some_field": "[\da-f]{8}-([\da-f]{4}-){3}[\da-f]{12}" }"#,
41        );
42    }
43}