Created
February 21, 2013 13:20
-
-
Save tobyink/5004689 to your computer and use it in GitHub Desktop.
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 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