Skip to content

Commit 6a1e0a0

Browse files
committed
feat(date): Support today/now
I would like to find a way to make `now` only capture the value once but not seeing a good way to do that. If this was being processed at a higher level, then we could have the user set it in the `Context`. A `lazy_static` wouldn't work because the process could be long running, serving multiple templates. Fixes #181
1 parent 027a67c commit 6a1e0a0

File tree

1 file changed

+35
-5
lines changed

1 file changed

+35
-5
lines changed

src/value/scalar.rs

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -237,11 +237,21 @@ mod friendly_date {
237237
}
238238

239239
fn parse_date(s: &str) -> Option<Date> {
240-
let formats = ["%d %B %Y %H:%M:%S %z", "%Y-%m-%d %H:%M:%S %z"];
241-
formats
242-
.iter()
243-
.filter_map(|f| Date::parse_from_str(s, f).ok())
244-
.next()
240+
match s {
241+
"now" | "today" => {
242+
let now = chrono::offset::Utc::now();
243+
let now = now.naive_utc();
244+
let now = chrono::DateTime::from_utc(now, chrono::offset::FixedOffset::east(0));
245+
Some(now)
246+
}
247+
_ => {
248+
let formats = ["%d %B %Y %H:%M:%S %z", "%Y-%m-%d %H:%M:%S %z"];
249+
formats
250+
.iter()
251+
.filter_map(|f| Date::parse_from_str(s, f).ok())
252+
.next()
253+
}
254+
}
245255
}
246256

247257
#[cfg(test)]
@@ -457,4 +467,24 @@ mod test {
457467
assert_eq!(empty, TRUE);
458468
assert!(empty.is_truthy());
459469
}
470+
471+
#[test]
472+
fn parse_date_empty_is_bad() {
473+
assert!(parse_date("").is_none());
474+
}
475+
476+
#[test]
477+
fn parse_date_bad() {
478+
assert!(parse_date("aaaaa").is_none());
479+
}
480+
481+
#[test]
482+
fn parse_date_now() {
483+
assert!(parse_date("now").is_some());
484+
}
485+
486+
#[test]
487+
fn parse_date_today() {
488+
assert!(parse_date("today").is_some());
489+
}
460490
}

0 commit comments

Comments
 (0)