chiark / gitweb /
TOML::Tiny: Provide hook for formatting DateTime objects
authorIan Jackson <ijackson@chiark.greenend.org.uk>
Mon, 4 May 2020 00:26:16 +0000 (01:26 +0100)
committerIan Jackson <ijackson@chiark.greenend.org.uk>
Tue, 5 May 2020 20:10:56 +0000 (21:10 +0100)
README.pod
lib/TOML/Tiny.pm
lib/TOML/Tiny/Writer.pm

index 78a96b9cff74acdf80bde26623d8e77026b01086..b04c46de8bffb84a7c1efe1ea1c5bbb8fdebe261 100644 (file)
@@ -184,6 +184,16 @@ Dates and times which weren't built with DateTime come out as strings.
 Specifying C<inflate_float>, C<inflate_integer>, and
 C<inflate_datetime> is likely to be helpful with this option.
 
+=item datetime_formatter
+
+When encoding a DateTime object, by default C<TOML::Tiny> will use the
+default formatter.  This is not right for TOML which requires RFC3339.
+If you have C<DateTime::Format::RFC3339> available, use this instead:
+
+  my $parser = TOML::Tiny->new(
+    datetime_formatter => DateTime::Format::RFC3339->new(),
+  );
+
 =back
 
 =head2 decode
index e68f548a776bdbb63c40f9b64e6bb4935e505ef3..89acb36695a4c6a365e21f23ef57ccb6fb5e40d3 100644 (file)
@@ -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<inflate_float>, C<inflate_integer>, and
 C<inflate_datetime> is likely to be helpful with this option.
 
+=item datetime_formatter
+
+When encoding a DateTime object, by default C<TOML::Tiny> will use the
+default formatter.  This is not right for TOML which requires RFC3339.
+If you have C<DateTime::Format::RFC3339> available, use this instead:
+
+  my $parser = TOML::Tiny->new(
+    datetime_formatter => DateTime::Format::RFC3339->new(),
+  );
+
 =back
 
 =head2 decode
index 831d2e5395583320954e8437346d9e3984e790d9..4e2275add7c5fead85b3ea332dda437dcc96c553 100644 (file)
@@ -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') {