NAME
Venus::Role::Coercible - Coercible Role
ABSTRACT
Coercible Role for Perl 5
SYNOPSIS
package Person;
use Venus::Class;
with 'Venus::Role::Coercible';
has 'name';
has 'father';
has 'mother';
has 'siblings';
sub coerce {
{
father => 'Person',
mother => 'Person',
name => 'Venus/String',
siblings => 'Person',
}
}
sub coerce_name {
my ($self, $code, @args) = @_;
return $self->$code(@args);
}
sub coerce_siblings {
my ($self, $code, $class, $value) = @_;
return [map $self->$code($class, $_), @$value];
}
package main;
my $person = Person->new(
name => 'me',
father => {name => 'father'},
mother => {name => 'mother'},
siblings => [{name => 'brother'}, {name => 'sister'}],
);
# $person
# bless({...}, 'Person')
# $person->name
# bless({...}, 'Venus::String')
# $person->father
# bless({...}, 'Person')
# $person->mother
# bless({...}, 'Person')
# $person->siblings
# [bless({...}, 'Person'), bless({...}, 'Person'), ...]
DESCRIPTION
This package modifies the consuming package and provides methods for hooking into object construction and coercing arguments into objects and values.
METHODS
This package provides the following methods:
coerce
coerce() (HashRef)
The coerce method, if defined, is called during object construction, or by the "coercion" method, and returns key/value pairs where the keys map to class attributes (or input parameters) and the values are Venus::Space compatible package names.
Since 0.01
- coerce example 1
-
package main; my $person = Person->new( name => 'me', ); my $coerce = $person->coerce; # { # father => "Person", # mother => "Person", # name => "Venus/String", # siblings => "Person", # }
coercion
coercion(HashRef $data) (HashRef)
The coercion method is called automatically during object construction but can be called manually as well, and is passed a hashref to coerce and return.
Since 0.01
- coercion example 1
-
package main; my $person = Person->new; my $coercion = $person->coercion({ name => 'me', }); # $coercion # {...} # $coercion->{name} # bless({...}, 'Venus::String') # $coercion->{father} # undef # $coercion->{mother} # undef # $coercion->{siblings} # undef
- coercion example 2
-
package main; my $person = Person->new; my $coercion = $person->coercion({ name => 'me', mother => {name => 'mother'}, siblings => [{name => 'brother'}, {name => 'sister'}], }); # $coercion # {...} # $coercion->{name} # bless({...}, 'Venus::String') # $coercion->{father} # undef # $coercion->{mother} # bless({...}, 'Person') # $coercion->{siblings} # [bless({...}, 'Person'), bless({...}, 'Person'), ...]
AUTHORS
Cpanery, cpanery@cpan.org
LICENSE
Copyright (C) 2021, Cpanery
Read the "license" file.