move rhailib to herolib
This commit is contained in:
70
rhailib/_archive/engine/examples/finance/example.rs
Normal file
70
rhailib/_archive/engine/examples/finance/example.rs
Normal file
@@ -0,0 +1,70 @@
|
||||
use engine::mock_db::create_mock_db;
|
||||
use engine::{create_heromodels_engine, eval_file};
|
||||
use rhai::Engine;
|
||||
use std::path::Path;
|
||||
|
||||
mod mock;
|
||||
use mock::seed_finance_data;
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
println!("Finance Rhai Example");
|
||||
println!("===================");
|
||||
|
||||
// Create a mock database
|
||||
let db = create_mock_db();
|
||||
|
||||
// Seed the database with some initial data
|
||||
seed_finance_data(db.clone());
|
||||
|
||||
// Create the Rhai engine using our central engine creator
|
||||
let mut engine = create_heromodels_engine(db.clone());
|
||||
|
||||
// Register timestamp helper functions
|
||||
register_timestamp_helpers(&mut engine);
|
||||
|
||||
// Get the path to the script
|
||||
let script_path = Path::new(file!())
|
||||
.parent()
|
||||
.unwrap()
|
||||
.join("finance_script.rhai");
|
||||
|
||||
println!("\nRunning script: {}", script_path.display());
|
||||
println!("---------------------");
|
||||
|
||||
// Run the script
|
||||
match eval_file(&engine, &script_path) {
|
||||
Ok(result) => {
|
||||
if !result.is_unit() {
|
||||
println!("\nScript returned: {:?}", result);
|
||||
}
|
||||
println!("\nScript executed successfully!");
|
||||
Ok(())
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("\nError running script: {}", err);
|
||||
Err(Box::new(std::io::Error::new(
|
||||
std::io::ErrorKind::Other,
|
||||
err.to_string(),
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Register timestamp helper functions with the engine
|
||||
fn register_timestamp_helpers(engine: &mut Engine) {
|
||||
use chrono::{TimeZone, Utc};
|
||||
|
||||
// Function to get current timestamp
|
||||
engine.register_fn("timestamp_now", || Utc::now().timestamp() as i64);
|
||||
|
||||
// Function to format a timestamp
|
||||
engine.register_fn("format_timestamp", |ts: i64| {
|
||||
let dt = Utc
|
||||
.timestamp_opt(ts, 0)
|
||||
.single()
|
||||
.expect("Invalid timestamp");
|
||||
dt.format("%Y-%m-%d %H:%M:%S UTC").to_string()
|
||||
});
|
||||
|
||||
println!("Timestamp helper functions registered successfully.");
|
||||
}
|
Reference in New Issue
Block a user