From 9df103679a9487abf4b1a9b28677e284004d71f2 Mon Sep 17 00:00:00 2001 From: Ian Jackson Date: Mon, 4 May 2020 01:26:16 +0100 Subject: [PATCH] TOML::Tiny: Provide hook for formatting DateTime objects --- README.pod | 10 ++++++++++ lib/TOML/Tiny.pm | 11 +++++++++++ lib/TOML/Tiny/Writer.pm | 3 ++- 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/README.pod b/README.pod index 78a96b9..b04c46d 100644 --- a/README.pod +++ b/README.pod @@ -184,6 +184,16 @@ Dates and times which weren't built with DateTime come out as strings. Specifying C, C, and C is likely to be helpful with this option. +=item datetime_formatter + +When encoding a DateTime object, by default C will use the +default formatter. This is not right for TOML which requires RFC3339. +If you have C available, use this instead: + + my $parser = TOML::Tiny->new( + datetime_formatter => DateTime::Format::RFC3339->new(), + ); + =back =head2 decode diff --git a/lib/TOML/Tiny.pm b/lib/TOML/Tiny.pm index e68f548..89acb36 100644 --- a/lib/TOML/Tiny.pm +++ b/lib/TOML/Tiny.pm @@ -52,6 +52,7 @@ sub encode { my ($self, $data) = @_; TOML::Tiny::Writer::to_toml($data, strict_arrays => $self->{strict_arrays}, + datetime_formatter => $self->{datetime_formatter}, no_string_guessing => $self->{no_string_guessing}, ); } @@ -241,6 +242,16 @@ Dates and times which weren't built with DateTime come out as strings. Specifying C, C, and C is likely to be helpful with this option. +=item datetime_formatter + +When encoding a DateTime object, by default C will use the +default formatter. This is not right for TOML which requires RFC3339. +If you have C available, use this instead: + + my $parser = TOML::Tiny->new( + datetime_formatter => DateTime::Format::RFC3339->new(), + ); + =back =head2 decode diff --git a/lib/TOML/Tiny/Writer.pm b/lib/TOML/Tiny/Writer.pm index 831d2e5..4e2275a 100644 --- a/lib/TOML/Tiny/Writer.pm +++ b/lib/TOML/Tiny/Writer.pm @@ -110,7 +110,8 @@ sub to_toml { } when (/DateTime/) { - return $data->stringify; + my $formatter = $param{datetime_formatter}; + return $formatter ? $formatter->format_datetime($data) : "$data"; } when ('Math::BigInt') { -- 2.30.2