handlebars-rust icon indicating copy to clipboard operation
handlebars-rust copied to clipboard

Add a hint about deserializing helper params

Open flxo opened this issue 7 years ago • 5 comments

This addition adds a note about the easy possiblity to work with helper parameters in their original type representation by using Deserialize.

flxo avatar Mar 09 '18 11:03 flxo

Sadly I had to add main to the doc text in order to use #[macro_use] for serde_derive. I didn't want to add the example to the other helper examples because it's just a use case of the helper parameters....

flxo avatar Mar 09 '18 12:03 flxo

hi @flxo , this looks like a good and convenient way for accessing json value, with type-safe guarantee. But it has a clone which I hope we can avoid in the doc. handlebars-rust already has too much clones that make me headache.

sunng87 avatar Mar 10 '18 02:03 sunng87

@sunng87 I stumbled across the clone as well. The point is that serde_json::from_value consumes a Value and ContextJson::value just borrows one that cannot be moved. If you have an idea to solve this - let me know!

I'm using this pattern in a code generator where the extra deserialisation doesn't hurt nor the clone and just had the idea to share this piece of code...

flxo avatar Mar 10 '18 08:03 flxo

By the way, how about adding a helper function to ContextJson that returns deserialized typed data? We can avoid the clone in this way. And I think it actually helps.

sunng87 avatar Mar 10 '18 14:03 sunng87

Sounds great, but I think calling clone cannot be avoided since the parameters are just borrowed in the helper and serde_json::from_value requires DeserializeOwned. Means that

 pub fn try_into(self) -> Result<T, RenderError> {

wouldn't work because it can never be called on a &ContextJson returned by param(...)

With the clone the helper function in ContextJson could look like this:

 pub fn try_into<T: ::serde::de::DeserializeOwned>(&self) -> Result<T, RenderError> {
     ::serde_json::from_value(self.value.clone())
         .map_err(|e| e.into())
}

flxo avatar Mar 10 '18 16:03 flxo