From ffad8516af0b91121dc0761c8026e0a12939a7d4 Mon Sep 17 00:00:00 2001 From: Michael Lohr Date: Wed, 3 May 2023 12:34:35 +0200 Subject: Implement default values for at() (#995) --- src/model/content.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) (limited to 'src/model') diff --git a/src/model/content.rs b/src/model/content.rs index 4af4e655..1bd19f14 100644 --- a/src/model/content.rs +++ b/src/model/content.rs @@ -252,8 +252,10 @@ impl Content { } /// Borrow the value of the given field. - pub fn at(&self, field: &str) -> StrResult { - self.field(field).ok_or_else(|| missing_field(field)) + pub fn at(&self, field: &str, default: Option) -> StrResult { + self.field(field) + .or(default) + .ok_or_else(|| missing_field_no_default(field)) } /// The content's label. @@ -582,8 +584,12 @@ impl Fold for Vec { } } -/// The missing key access error message. +/// The missing key access error message when no default value was given. #[cold] -fn missing_field(key: &str) -> EcoString { - eco_format!("content does not contain field {:?}", Str::from(key)) +fn missing_field_no_default(key: &str) -> EcoString { + eco_format!( + "content does not contain field {:?} and \ + no default value was specified", + Str::from(key) + ) } -- cgit v1.2.3