Search code examples
perlperl-module

Using Type::Tiny, is there a way to stringify, deflate or uncoerce a date type?


I've built a module that uses Type::Tiny and it's working fine.

Now I have to write a TO_JSON subroutine and I'm hoping I don't have to write a deflate method for each piece of data. Is there a way to define a deflation method in the type definition with Type::Tiny? An 'uncoerce' so to speak. I haven't found anything in the docs but I may just not be looking for the right keyword.

I am not using an object frame like Moo or Moose, but I am using an object for the data.

A simplified example looks like

package My::Object::Types;
# the usual stuff, strict, etc.
my $meta = __PACKAGE__->meta;
my $_Date = Type::Tiny::Class->new( class => 'Time::Piece' );
my $_Due = $meta->add_type(
  name => 'Due',
  parent => $_Date,
);

package My::Object;
# again, the usual strict, warnings, etc.
sub new {
  my ( $class, $args ) = @_;
  my $self = bless {}, $class;

  for my $attr ( keys %$args ) {
    my $type = ucfirst $attr;
    my $set_attribute = "set_$attr";

    *$set_attribute = sub {
      my ( $self, $value ) = @_;
      $value = $self->$type->assert_coerce( $value ) if $self->$type->has_coercion;
      my $invalid = $self->$type->validate( $value );
      carp $invalid && return if $invalid;
      $self->{data}{$attr} = $value;
    };

    $attr = sub { return $_[0]->{data}{$attr} };
  }

  return $self;
}

Solution

  • Answering my own question ... I must write my own deflate methods.