MooX::Role::Reconstruct - Reconstruct Moo Objects
# in a module package MyModule; use Moo; with qw( MooX::Role::Reconstruct ); has row_id => ( is => 'ro', init_arg => undef, ); has foo => ( is => 'rw', ); 1; # and in a script my $row_ref = $sth->fetchrow_hashref(); # create a new object bypassing any init_arg restrictions my $obj = MyModule->reconstruct( $row_ref );
It is often desirable to create an object from a database row or a decoded JSON object. However, it is quite likely that you might have declared some attributes with init_arg => undef so simply calling class->new( %hash ) will fail.
init_arg => undef
class->new( %hash )
This module makes it possible by providing a constructor that will ignore all init_arg directives. This behavior can be disabled on a case-by-case basis by specifying keep_init => 1 in the has structure for a given attribute as shown below:
init_arg
keep_init => 1
has
has foo => ( is => 'ro', default => 'bar', init_arg => 'baz', keep_init => 1, );
In this case, the noraml behavior of taking the initializer value from baz if it is present will be retained.
baz
BUILDARGS and BUILD will be called as they would be if class->new had been used, as will any coerce and/or isa specifiers. (This presumes that one has written sensible coerce and isa conditions.)
BUILDARGS
BUILD
class->new
coerce
isa
The module installs a method named reconstruct by default.
reconstruct
Note: Any naming conflicts will show up as a Subroutine redefined error.
Subroutine redefined
This Role requires that Moo be loaded prior to use. The module will die otherwise.
die
Please report any bugs or feature requests through the issue tracker at https://github.com/boftx/MooX-Role-Reconstruct/issues. You will be notified automatically of any progress on your issue.
GitHub: https://github.com/boftx/MooX-Role-Reconstruct
Sub::Quote, Sub::Defer, Role::Tiny
This module is based on ideas in MooseX::UnsafeConstructable.
Jim Bacon <jim@nortx.com>
Copyright (C) 2014, Jim Bacon
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.16 or, at your option, any later version of Perl 5 you may have available.
To install MooX::Role::Reconstruct, copy and paste the appropriate command in to your terminal.
cpanm
cpanm MooX::Role::Reconstruct
CPAN shell
perl -MCPAN -e shell install MooX::Role::Reconstruct
For more information on module installation, please visit the detailed CPAN module installation guide.