Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
use v5.14;
use Test::More;
package MooseX::IgnoreFalse::Trait::Attribute
{
use Moose::Role;
after _process_options => sub
{
my ($class, $name, $options) = @_;
if (my $orig = $options->{initializer})
{
$options->{initializer} = sub
{
my ($instance, $value, $setter) = @_;
my $meta = $instance->meta->get_attribute($name);
$value ? $orig->( $instance, $value, $setter ) :
$meta->has_default ? $orig->( $instance, $meta->default($instance), $setter ) :
$meta->has_builder ? $orig->( $instance, $meta->_call_builder($instance), $setter ) :
();
}
}
else
{
$options->{initializer} = sub
{
my ($instance, $value, $setter) = @_;
my $meta = $instance->meta->get_attribute($name);
$value ? $setter->( $value ) :
$meta->has_default ? $setter->( $meta->default($instance) ) :
$meta->has_builder ? $setter->( $meta->_call_builder($instance) ) :
();
}
}
};
}
package Foo
{
use Moose;
has foo => (
traits => ['MooseX::IgnoreFalse::Trait::Attribute'],
is => 'ro',
default => 'whatever',
);
}
is(Foo->new(foo => 'xyz')->foo, 'xyz');
is(Foo->new(foo => '0')->foo, 'whatever');
is(Foo->new(foo => '')->foo, 'whatever');
is(Foo->new(foo => undef)->foo, 'whatever');
done_testing;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment