From: Florian Ragwitz Date: Thu, 30 Jul 2009 06:09:19 +0000 (+0200) Subject: WIP: Add a Code attribute helper. X-Git-Tag: 0.90~63 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=cdf3cae66c3eb1c17df33744fcd70ee0e43ff85a;p=gitmo%2FMoose.git WIP: Add a Code attribute helper. --- diff --git a/lib/Moose/Meta/Attribute/Native.pm b/lib/Moose/Meta/Attribute/Native.pm index ebfe231..4b4b833 100644 --- a/lib/Moose/Meta/Attribute/Native.pm +++ b/lib/Moose/Meta/Attribute/Native.pm @@ -4,7 +4,7 @@ our $VERSION = '0.89_02'; $VERSION = eval $VERSION; our $AUTHORITY = 'cpan:STEVAN'; -my @trait_names = qw(Bool Counter Number String Array Hash); +my @trait_names = qw(Bool Counter Number String Array Hash Code); for my $trait_name (@trait_names) { my $trait_class = "Moose::Meta::Attribute::Native::Trait::$trait_name"; diff --git a/lib/Moose/Meta/Attribute/Trait/Native/Code.pm b/lib/Moose/Meta/Attribute/Trait/Native/Code.pm new file mode 100644 index 0000000..cced18e --- /dev/null +++ b/lib/Moose/Meta/Attribute/Trait/Native/Code.pm @@ -0,0 +1,23 @@ +package Moose::Meta::Attribute::Trait::Native::Code; +use Moose::Role; +use Moose::Meta::Attribute::Trait::Native::MethodProvider::Code; + +our $VERSION = '0.87'; +$VERSION = eval $VERSION; +our $AUTHORITY = 'cpan:STEVAN'; + +with 'Moose::Meta::Attribute::Trait::Native'; + +has method_provider => ( + is => 'ro', + isa => 'ClassName', + predicate => 'has_method_provider', + default => 'Moose::Meta::Attribute::Trait::Native::MethodProvider::Code', +); + +sub _default_is { 'ro' } +sub _helper_type { 'CodeRef' } + +no Moose::Role; + +1; diff --git a/lib/Moose/Meta/Attribute/Trait/Native/MethodProvider/Code.pm b/lib/Moose/Meta/Attribute/Trait/Native/MethodProvider/Code.pm new file mode 100644 index 0000000..34cd020 --- /dev/null +++ b/lib/Moose/Meta/Attribute/Trait/Native/MethodProvider/Code.pm @@ -0,0 +1,15 @@ +package Moose::Meta::Attribute::Trait::Native::MethodProvider::Code; +use Moose::Role; + +our $VERSION = '0.87'; +$VERSION = eval $VERSION; +our $AUTHORITY = 'cpan:STEVAN'; + +sub execute : method { + my ( $attr, $reader, $writer ) = @_; + return sub { $reader->(@_)->(@_) }; +} + +no Moose::Role; + +1; diff --git a/t/070_attribute_traits/209_trait_code.t b/t/070_attribute_traits/209_trait_code.t new file mode 100644 index 0000000..832f48b --- /dev/null +++ b/t/070_attribute_traits/209_trait_code.t @@ -0,0 +1,24 @@ +use strict; +use warnings; + +use Test::More tests => 2; + +{ + package Thingy; + use Moose; + + has callback => ( + traits => ['Code'], + is => 'ro', + isa => 'CodeRef', + required => 1, + handles => { 'invoke_callback' => 'execute' }, + ); +} + +my $i = 0; +my $thingy = Thingy->new(callback => sub { ++$i }); + +is($i, 0); +$thingy->invoke_callback; +is($i, 1);