Last active
March 3, 2021 08:04
-
-
Save j1n3l0/0e63cebbed0b3a2ef9acf038473c1278 to your computer and use it in GitHub Desktop.
Coerce an attribute from Undef|EmptyStr to a default value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use Test2::V0; | |
package Api::Client 1.0 { | |
use Moose; | |
use Moose::Util::TypeConstraints; | |
use Readonly; | |
Readonly my $DEFAULT_HOSTNAME => 'api.example.com'; | |
subtype 'EmptyStr', as 'Str', where { /^$/ }; | |
subtype 'Hostname', as 'Str', where { /^.+$/ }; | |
coerce 'Hostname', | |
from 'EmptyStr', via {$DEFAULT_HOSTNAME}, | |
from 'Undef', via {$DEFAULT_HOSTNAME}; | |
has hostname => | |
( coerce => 1, is => 'ro', isa => 'Hostname', default => $DEFAULT_HOSTNAME ); | |
}; | |
subtest 'Instantiating a new Api::Client' => sub { | |
is( Api::Client->new(), | |
object { call hostname => 'api.example.com' }, | |
'should have the correct "hostname" with ()', | |
); | |
is( Api::Client->new( hostname => 'api-eu.example.com' ), | |
object { call hostname => 'api-eu.example.com' }, | |
'should have the correct "hostname" with ( hostname => "api-eu.example.com" )', | |
); | |
is( Api::Client->new( hostname => undef ), | |
object { call hostname => 'api.example.com' }, | |
'should have the correct "hostname" with ( hostname => undef )', | |
); | |
is( Api::Client->new( hostname => "" ), | |
object { call hostname => 'api.example.com' }, | |
'should have the correct "hostname" with ( hostname => "" )', | |
); | |
}; | |
done_testing(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment