in reply to Types::DateTime, DateTimeUTC->plus_coercions( Format['ISO8601'] ), output format override question

As per ikegami's answer (Re: Types::DateTime, DateTimeUTC->plus_coercions( Format['ISO8601'] ), output format override question), you want to set a formatter on the DateTime object.

$cowtime->timestamp->set_formatter($formatter);

But you probably want your CowTime class to be doing that automatically. You can do that with triggers:

use 5.12.0; package CowTime { use Moo; use Types::DateTime -all; has timestamp => is => "ro", isa => DateTimeUTC->plus_coercions( Format['ISO8601'] ), coerce => 1, trigger => sub { my ($self, $value) = @_; state $formatter = DateTime::Format::MyFormatter->new; $value->set_formatter($formatter); }; 1; };

The trigger is a coderef which gets called any time you set the value of an attribute. (Though it's not set if the attribute is set by a default/builder.)

  • Comment on Re: Types::DateTime, DateTimeUTC->plus_coercions( Format['ISO8601'] ), output format override question
  • Select or Download Code

Replies are listed 'Best First'.
Re^2: Types::DateTime, DateTimeUTC->plus_coercions( Format['ISO8601'] ), output format override question
by ikegami (Patriarch) on Dec 26, 2019 at 09:04 UTC

    Though it's not set if the attribute is set by a default/builder.

    That makes this a particularly bad solution, then.

      Why? OP isn't using a default or builder. (Not in the example anyway.)

        It violates the fundamental principle of least surprise. The code fails in subtle fashion.