WIP: Add a Code attribute helper.
Florian Ragwitz [Thu, 30 Jul 2009 06:09:19 +0000 (08:09 +0200)]
lib/Moose/Meta/Attribute/Native.pm
lib/Moose/Meta/Attribute/Trait/Native/Code.pm [new file with mode: 0644]
lib/Moose/Meta/Attribute/Trait/Native/MethodProvider/Code.pm [new file with mode: 0644]
t/070_attribute_traits/209_trait_code.t [new file with mode: 0644]

index ebfe231..4b4b833 100644 (file)
@@ -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 (file)
index 0000000..cced18e
--- /dev/null
@@ -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 (file)
index 0000000..34cd020
--- /dev/null
@@ -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 (file)
index 0000000..832f48b
--- /dev/null
@@ -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);