basic/
basic.rs

1use script_format::{
2    // The crate re-exports the Rhai engine for convenience
3    rhai::{CustomType, TypeBuilder},
4    FormattingEngine,
5};
6
7// Derive the `CustomType` trait to enable Rhai to access the fields of the struct
8#[derive(Clone, CustomType)]
9struct Person {
10    pub name: String,
11    pub age: i32,
12}
13
14fn main() {
15    // Create a new `FormattingEngine` instance with debug mode disabled
16    let mut engine = FormattingEngine::new(true);
17    // Register the custom type so the Rhai engine can access it
18    engine.build_type::<Person>();
19
20    let person = Person {
21        name: "Alice".into(),
22        age: 30,
23    };
24
25    let script = r#"
26SET_INDENT(".. ");                         // sets the current indent string to ".. "
27~ "Person Details:";                       // - emits a single message
28~ NL;                                      // NL emits a newline
29~ IND ++ "Name: " ++ person.name ++ NL;    // ++ emits the message and concatenates it
30
31// custom operator then_emit emits a message conditionally
32~ IND(2) ++ person.name contains "Alice" then_emit ("- Hello Alice" ++ NL);
33
34~ IND ++ "Age: " ++ person.age ++ NL;      // ++ automatically converts the values to strings
35~ IND(2);                                  // custom operator IND indents the message
36~ person.age > 18 then_emit ("- Adult" ++ NL); // custom operator then_emit emits a message conditionally
37
38~ [1, 2, 3] contains 2 then_emit ("- Contains 2" ++ NL);
39~ [1, 2, 3] any 2 then_emit ("- Some values are 2" ++ NL);
40~ [1, 2, 3] all 2 then_emit ("- All values are 2" ++ NL);
41~ [1, 2, 3] none 2 then_emit ("- No 2 found" ++ NL);
42"#;
43
44    let expected = r#"
45Person Details:
46.. Name: Alice
47.. .. - Hello Alice
48.. Age: 30
49.. .. - Adult
50- Contains 2
51- Some values are 2
52"#
53    .trim_start();
54
55    // Execute the Rhai script to format the person's details
56    let result = engine.format("person", person, script);
57    assert_eq!(result.unwrap(), expected);
58}