@@ -8,28 +8,33 @@ use std::{
88 hash:: BuildHasher ,
99 result,
1010} ;
11- /// Converts a model instance into a consistent yaml.
12- ///
13- /// # Errors
14- ///
15- /// Will return `Err` if there is an issue converting an `instance` into YAML (w/o annotation).
16- pub fn to_yaml < T : Serialize > ( instance : & T ) -> Result < String > {
17- let mapping: IndexMap < String , Value > = serde_yaml:: from_str ( & serde_yaml:: to_string ( instance) ?) ?; // cast to map
18- let mut yaml = serde_yaml:: to_string (
19- & mapping
20- . iter ( )
21- . filter_map ( |( k, v) | match & * * k {
22- "annotation" | "hash" => None ,
23- "pod" | "pod_job" => Some ( ( k, v[ "hash" ] . clone ( ) ) ) ,
24- _ => Some ( ( k, v. clone ( ) ) ) ,
25- } )
26- . collect :: < IndexMap < _ , _ > > ( ) ,
27- ) ?; // skip fields and convert refs to hash pointers
28- yaml. insert_str (
29- 0 ,
30- & format ! ( "class: {}\n " , get_type_name:: <T >( ) . to_snake_case( ) ) ,
31- ) ; // replace class at top
32- Ok ( yaml)
11+
12+ /// Trait to handle serialization to yaml for `OrcaPod` models
13+ pub trait ToYaml : Serialize + Sized {
14+ /// Serializes the instance to a YAML string.
15+ /// # Errors
16+ /// Will return `Err` if it fail to serialize instance to string
17+ fn to_yaml ( & self ) -> Result < String > {
18+ let mapping: IndexMap < String , Value > = serde_yaml:: from_str ( & serde_yaml:: to_string ( self ) ?) ?; // cast to map
19+ let mut yaml = serde_yaml:: to_string (
20+ & mapping
21+ . iter ( )
22+ . filter_map ( |( k, v) | Self :: process_field ( k, v) )
23+ . collect :: < IndexMap < _ , _ > > ( ) ,
24+ ) ?; // skip fields and convert refs to hash pointers
25+ yaml. insert_str (
26+ 0 ,
27+ & format ! ( "class: {}\n " , get_type_name:: <Self >( ) . to_snake_case( ) ) ,
28+ ) ; // replace class at top
29+ Ok ( yaml)
30+ }
31+
32+ /// Filter out which field to serialize and which to omit
33+ ///
34+ /// # Returns
35+ /// (`field_name`, `field_value`): to be pass to `to_yaml` for serialization
36+ /// None: to skip
37+ fn process_field ( field_name : & str , field_value : & Value ) -> Option < ( String , Value ) > ;
3338}
3439
3540pub ( crate ) fn serialize_hashmap < S , K : Ord + Serialize , V : Serialize , BH : BuildHasher > (
0 commit comments