MooseX::LazyCoercion - Coercion deferred to attribute call time
version 0.002
# # with built-in type constraints # package My::Foo; use MooseX::LazyCoercion; subtype 'My::DateTime' => as 'DateTime'; coerce 'My::DateTime' => from 'Int', via { DateTime->from_epoch( epoch => $_ ) }; has_lazily_coerced dt => ( is => 'ro', isa => 'My::DateTime', ); package main; my $foo = My::Foo->new( dt => time() ); my $dt = $foo->{dt} # uncoerced, returns undef my $dt = $foo->dt # coerced, returns DateTime object # # with MooseX::Types type constraints # package My::Foo; use MooseX::Types::DateTime qw(DateTime); has_lazily_coerced dt => ( is => 'ro', isa => DateTime, ); package main; my $foo = My::Foo->new( dt => time() ) my $dt = $foo->{dt} # uncoerced, returns undef my $dt = $foo->dt # coerced, returns DateTime object
Moose has the feature of lazy attribute creation, that is: The value of an attribute is created only at the moment when it is first called. Moose has another cool feature, type coercions, which allows one to define rules on how to derive the type of value specified in the "isa" parameter to "has" from different data structures. Unfortunately, this breaks the laziness of attribute creation, since all coercions are performed at BUILD time.
This module allows one to defer the coercion of an attribute to the time when it is first called. It does so by shadowing the value passed to the init_arg of the attribute to a temporary attribute and coercing that when the original attribute is called.
MooseX::LazyCoercion can introspect both native typeconstraints and the type decorators used by MooseX::Types to determine if a value passed to the shadow attribute can be coerced. This way, you have the benefit of type checking without the overhead of type coercion performed at build time.
MooseX::LazyCoercion - Lazy coercions for Moose TypeConstraints
Konstantin Baierer <kba@cpan.org>
This software is copyright (c) 2012 by Konstantin Baierer.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
To install MooseX::LazyCoercion, copy and paste the appropriate command in to your terminal.
cpanm
cpanm MooseX::LazyCoercion
CPAN shell
perl -MCPAN -e shell install MooseX::LazyCoercion
For more information on module installation, please visit the detailed CPAN module installation guide.