Skip to content

Instantly share code, notes, and snippets.

@j1n3l0
Last active March 3, 2021 08:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j1n3l0/0e63cebbed0b3a2ef9acf038473c1278 to your computer and use it in GitHub Desktop.
Save j1n3l0/0e63cebbed0b3a2ef9acf038473c1278 to your computer and use it in GitHub Desktop.
Coerce an attribute from Undef|EmptyStr to a default value
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