Skip to content
Deflates Moose attributes to a string
Pull request Compare This branch is 2 commits ahead, 29 commits behind monken:master.
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.



 package Test;

 use Moose;
 use DateTime;

 use MooseX::Attribute::Deflator;

 deflate 'DateTime', via { $_->epoch };
 inflate 'DateTime', via { DateTime->from_epoch( epoch => $_ ) };

 no MooseX::Attribute::Deflator;

 use MooseX::Attribute::Deflator::Moose;

 has now => ( is => 'rw', 
            isa => 'DateTime', 
            default => sub { DateTime->now }, 
            traits => ['Deflator'] );

 has hash => ( is => 'rw', 
               isa => 'HashRef', 
               default => sub { { foo => 'bar' } }, 
               traits => ['Deflator'] );

 package main;

 use Test::More;

 my $obj = Test->new;

     my $attr = $obj->meta->get_attribute('now');
     my $deflated = $attr->deflate($obj);
     like($deflated, qr/^\d+$/);

     my $inflated = $attr->inflate($obj, $deflated);
     isa_ok($inflated, 'DateTime');

     my $attr = $obj->meta->get_attribute('hash');
     my $deflated = $attr->deflate($obj);
     is($deflated, '{"foo":"bar"}');

     my $inflated = $attr->inflate($obj, $deflated);
     is_deeply($inflated, {foo => 'bar'})



This module consists of a a registry (MooseX::Attribute::Deflator::Registry) an attribute trait MooseX::Attribute::Deflator::Meta::Role::Attribute and predefined deflators and inflators for Moose MooseX::Attribute::Deflator::Moose and MooseX::Types::Strutured MooseX::Attribute::Deflator::Structured. This class is just sugar to set the inflators and deflators.

Unlike coerce, you don't need to create a deflator and inflator for every type. Instead this module will bubble up the type hierarchy and use the first deflator or inflator it finds.

This comes at a cost: Union types are not supported.


 deflate 'DateTime', via { $_->epoch };
 inflate 'DateTime', via { DateTime->from_epoch( epoch => $_ ) };

Defines a deflator or inflator for a given type constraint. This can also be a type constraint defined via MooseX::Types and parameterized types.

The function supplied to via is called with $_ set to the attribute's value and with the following arguments:


The attribute on which this deflator/inflator has been called


The type constraint attached to the attribute


A code reference to the deflate or inflate function. E.g. this is handy if you want to call the type's parent's parent inflate or deflate method:

 deflate 'MySubSubType', via {
    my ($attr, $constraint, $deflate) = @_;
    return $deflate->($_, $constraint->parent->parent);

The object instance on which this deflator/inflator has been called


Any other arguments added to "inflate" in MooseX::Attribute::Deflator::Meta::Role::Attribute or "deflate" in MooseX::Attribute::Deflator::Meta::Role::Attribute.

Something went wrong with that request. Please try again.