-
-
Notifications
You must be signed in to change notification settings - Fork 114
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
ObjectBuilder: add property_if(), property_if_some(), property_from_i…
…ter() ... ... & property_if_not_empty() This commit adds functions to improve usability when setting properties. **`property_if()`** allows setting a property from an `Option` only if a given `predicate` evaluates to `true`. Otherwise, the `Object`'s default value or any previously set value is kept. **`property_if_some()`** allows setting a property from an `Option` only if the `Option` is `Some`. Otherwise, the `Object`'s default value or any previously set value is kept. For instance, assuming an `Args` `struct` which was built from the application's CLI arguments: ```rust let args = Args { name: Some("test"), anwser: None, }; ``` ... without this change, we need to write something like this: ```rust let mut builder = Object::builder::<SimpleObject>(); if let Some(ref name) = args.name { builder = builder.property("name", name) } if let Some(ref answer) = args.answer { builder = builder.property("answer", &args.answer) } let obj = builder.build(); ``` With `property_if_some()`, we can write: ```rust let obj = Object::builder::<SimpleObject>() .property_if_some("name", &args.name) .property_if_some("answer", &args.answer) .build(); ``` **`property_from_iter()`** allows building a collection-like `Value` property from a collection of items: ```rust let obj = Object::builder::<SimpleObject>() .property_from_iter::<ValueArray>("array", ["val0", "val1"]) .build(); ``` **`property_if_not_empty()`** allows building a collection-like `Value` property from a collection of items but does nothing if the provided collection if empty, thus keeping the default value of the property, if any: ```rust let obj = Object::builder::<SimpleObject>() .property_if_not_empty::<ValueArray>("array", ["val0", "val1"]) .build(); ```
- Loading branch information
Showing
2 changed files
with
226 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters