diff options
| author | 魏曹先生 <1992414357@qq.com> | 2026-05-16 16:24:55 +0800 |
|---|---|---|
| committer | 魏曹先生 <1992414357@qq.com> | 2026-05-16 16:24:55 +0800 |
| commit | a5647e89bc5110a07c8f3c695c3c9582aa31d354 (patch) | |
| tree | 63c5be475c53b578c7ff5fe0d454899c0aa315b1 /examples/example-resources/src | |
| parent | f7964129a5b5e41fd6da0f191a7e37e93bd36814 (diff) | |
Simplify example imports to use prelude and add resources example
Add a new example demonstrating global resource injection in chain
functions,
and update all existing examples to import from `mingling::prelude`
instead
of individual macro paths. Also add `example-resources` to the workspace
exclude list.
Diffstat (limited to 'examples/example-resources/src')
| -rw-r--r-- | examples/example-resources/src/main.rs | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/examples/example-resources/src/main.rs b/examples/example-resources/src/main.rs new file mode 100644 index 0000000..63ebfe6 --- /dev/null +++ b/examples/example-resources/src/main.rs @@ -0,0 +1,57 @@ +//! `Mingling` Example - Global Resource Injection +//! +//! This example demonstrates how to use global resource injection in `#[chain]` functions. +//! You can inject both immutable (`&T`) and mutable (`&mut T`) references to global resources. +//! +//! # How to Run +//! ```bash +//! cargo run --manifest-path ./examples/example-resources/Cargo.toml -- setup +//! ``` + +use mingling::prelude::*; +use std::{env::current_dir, path::PathBuf}; + +// Define a resource for storing global state +#[derive(Default, Clone)] +pub struct MyResource { + current_dir: PathBuf, +} + +fn main() { + let mut program = ThisProgram::new(); + + // Add the resource to the program + program.with_resource(MyResource::default()); + + program.with_dispatcher(SetupCommand); + program.exec_and_exit(); +} + +dispatcher!("setup", SetupCommand => SetupEntry); +pack!(StateRead = ()); +pack!(ResultCurrentDir = PathBuf); + +#[chain] +fn setup( + _prev: SetupEntry, + resource: &mut MyResource, // Import the resource into `setup` +) -> NextProcess { + // Set the global resource + resource.current_dir = current_dir().unwrap(); + + StateRead::default() +} + +#[chain] +fn read(_prev: StateRead, resource: &MyResource) -> NextProcess { + // Read the global resource + let current_dir = resource.current_dir.clone(); + ResultCurrentDir::new(current_dir).to_render() +} + +#[renderer] +fn render_current_dir(dir: ResultCurrentDir) { + r_println!("Current dir: {}", dir.to_string_lossy()) +} + +gen_program!(); |
