HeroModels Rhai Engine (engine)
The engine crate provides a central Rhai scripting engine for the HeroModels project. It offers a unified way to interact with various HeroModels modules (like Calendar, Flow, Legal, etc.) through Rhai scripts, leveraging a shared database connection.
Overview
This crate facilitates:
- Centralized Engine Creation: A function
create_heromodels_engineto instantiate a Rhai engine pre-configured with common settings and all enabled HeroModels modules. - Modular Registration: HeroModels modules (Calendar, Flow, etc.) can be registered with a Rhai engine based on feature flags.
- Script Evaluation Utilities: Helper functions for compiling Rhai scripts into Abstract Syntax Trees (ASTs) and for evaluating scripts or ASTs.
- Mock Database: Includes a
mock_dbmodule for testing and running examples without needing a live database.
Core Components & Usage
Library (src/lib.rs)
-
create_heromodels_engine(db: Arc<OurDB>) -> Engine: Creates and returns a newrhai::Engineinstance. This engine is configured with default settings (e.g., max expression depths, string/array/map sizes) and then all available HeroModels modules (controlled by feature flags) are registered with it, using the provideddb(anArc<OurDB>) instance. -
register_all_modules(engine: &mut Engine, db: Arc<OurDB>): Registers all HeroModels modules for which features are enabled (e.g.,calendar,flow,legal,projects,biz) with the given Rhaiengine. Each module is passed the shareddbinstance. -
eval_script(engine: &Engine, script: &str) -> Result<rhai::Dynamic, Box<rhai::EvalAltResult>>: A utility function to directly evaluate a Rhai script string using the providedengine. -
compile_script(engine: &Engine, script: &str) -> Result<AST, Box<rhai::EvalAltResult>>: Compiles a Rhai script string into anAST(Abstract Syntax Tree) for potentially faster repeated execution. -
run_ast(engine: &Engine, ast: &AST, scope: &mut Scope) -> Result<rhai::Dynamic, Box<rhai::EvalAltResult>>: Runs a pre-compiledASTwith a givenscopeusing the providedengine. -
mock_dbmodule: Providescreate_mock_db()which returns anArc<OurDB>instance suitable for testing and examples. This allows scripts that interact with database functionalities to run without external database dependencies.
Basic Usage
use std::sync::Arc;
use engine::{create_heromodels_engine, eval_script};
use engine::mock_db::create_mock_db; // For example usage
use heromodels::db::hero::OurDB; // Actual DB type
// Create a mock database (or connect to a real one)
let db: Arc<OurDB> = create_mock_db();
// Create the Rhai engine with all enabled modules registered
let engine = create_heromodels_engine(db);
// Run a Rhai script
let script = r#"
// Example: Assuming 'calendar' feature is enabled
let cal = new_calendar("My Test Calendar");
cal.set_description("This is a test.");
print(`Created calendar: ${cal.get_name()}`);
cal.get_id() // Return the ID
"#;
match eval_script(&engine, script) {
Ok(val) => println!("Script returned: {:?}", val),
Err(err) => eprintln!("Script error: {}", err),
}
Using Specific Modules Manually
If you need more fine-grained control or only want specific modules (and prefer not to rely solely on feature flags at compile time for create_heromodels_engine), you can initialize an engine and register modules manually:
use std::sync::Arc;
use rhai::Engine;
use engine::mock_db::create_mock_db; // For example usage
use heromodels::db::hero::OurDB;
// Import the specific module registration function
use heromodels::models::calendar::register_calendar_rhai_module;
// Create a mock database
let db: Arc<OurDB> = create_mock_db();
// Create a new Rhai engine
let mut engine = Engine::new();
// Register only the calendar module
register_calendar_rhai_module(&mut engine, db.clone());
// Now you can use calendar-related functions in your scripts
let result = engine.eval::<String>(r#" let c = new_calendar("Solo Cal"); c.get_name() "#);
match result {
Ok(name) => println!("Calendar name: {}", name),
Err(err) => eprintln!("Error: {}", err),
}
Examples
This crate includes several examples demonstrating how to use different HeroModels modules with Rhai. Each example typically requires its corresponding feature to be enabled.
calendar_example: Working with calendars, events, and attendees (requirescalendarfeature).flow_example: Working with flows, steps, and signature requirements (requiresflowfeature).finance_example: Working with financial models (requiresfinancefeature).- (Additional examples for
legal,projects,bizwould follow the same pattern if present).
To run an example (e.g., calendar_example):
cargo run --example calendar_example --features calendar
(Note: Examples in Cargo.toml already specify required-features, so simply cargo run --example calendar_example might suffice if those features are part of the default set or already enabled.)
Features
The crate uses feature flags to control which HeroModels modules are compiled and registered:
calendar: Enables the Calendar module.finance: Enables the Finance module.flow: Enables the Flow module.legal: Enables the Legal module.projects: Enables the Projects module.biz: Enables the Business module.
The default features are ["calendar", "finance"]. You can enable other modules by specifying them during the build or in your project's Cargo.toml if this engine crate is a dependency.
Dependencies
Key dependencies include:
rhai: The Rhai scripting engine.heromodels: Provides the core data models and database interaction logic, including the Rhai registration functions for each module.heromodels_core: Core utilities for HeroModels.chrono: For date/time utilities.heromodels-derive: Procedural macros used by HeroModels.
License
This crate is part of the HeroModels project and shares its license.