//! Example Setup //! //! > This example demonstrates how to build a custom Setup that encapsulates a //! > group of related resources and registers them with `with_resource`. use mingling::{Program, macros::program_setup, prelude::*}; use std::io::Write; // A group of related resources — here, the demo app's identity. // Resource types are plain structs: any `Default + Clone + Send + Sync` type // can be used as a resource, and it is identified by its type. #[derive(Default, Clone)] struct ResAppName { name: String, } #[derive(Default, Clone)] struct ResAppVersion { version: String, } #[derive(Default, Clone)] struct ResGreetingPrefix { prefix: String, } fn main() { let mut program = ThisProgram::new(); // --------- IMPORTANT --------- // Introduce `CustomSetup` generated by `custom_setup` program.with_setup(CustomSetup); // --------- IMPORTANT --------- program.exec_and_exit(); } // --------- IMPORTANT --------- // Define `CustomSetup` (inferred from `custom_setup`) // Package part of the program construction logic into this type for modular // management — e.g. register a group of related resources here. #[program_setup] fn custom_setup(program: &mut Program) { program.with_resource(ResAppName { name: "mingling".to_string(), }); program.with_resource(ResAppVersion { version: "0.5.0".to_string(), }); program.with_resource(ResGreetingPrefix { prefix: "Hello".to_string(), }); } // --------- IMPORTANT --------- dispatcher!("greet", EntryGreet); #[derive(Grouped, Wrap)] pub struct ResultGreeting(String); /// Chain: reads the `ResAppName` and `ResAppVersion` resources. #[chain] fn handle_greet(args: EntryGreet, app: &ResAppName, version: &ResAppVersion) -> Next { let who = args .0 .first() .cloned() .unwrap_or_else(|| "World".to_string()); let greeting: ResultGreeting = format!("{} from {} v{}", who, app.name, version.version).into(); greeting.into() } /// Renderer: injects the `ResGreetingPrefix` resource to decorate the output. #[renderer] fn render_greet(greeting: ResultGreeting, prefix: &ResGreetingPrefix) -> RenderResult { let mut render_result = RenderResult::new(); writeln!(render_result, "{}, {}!", prefix.prefix, *greeting).ok(); render_result } gen_program!();