added YourClass->meta->add_attribute(foo => (is => 'ro', isa => 'Str')); support.
Tokuhiro Matsuno [Wed, 4 Mar 2009 23:49:51 +0000 (23:49 +0000)]
lib/Mouse.pm
lib/Mouse/Meta/Class.pm
t/046-meta-add_attribute.t [new file with mode: 0644]

index 2281d35..67c1e77 100644 (file)
@@ -29,30 +29,7 @@ sub extends { Mouse::Meta::Class->initialize(caller)->superclasses(@_) }
 
 sub has {
     my $meta = Mouse::Meta::Class->initialize(caller);
-
-    my $names = shift;
-    $names = [$names] if !ref($names);
-    my $metaclass = 'Mouse::Meta::Attribute';
-    my %options = @_;
-
-    if ( my $metaclass_name = delete $options{metaclass} ) {
-        my $new_class = Mouse::Util::resolve_metaclass_alias(
-            'Attribute',
-            $metaclass_name
-        );
-        if ( $metaclass ne $new_class ) {
-            $metaclass = $new_class;
-        }
-    }
-
-    for my $name (@$names) {
-        if ($name =~ s/^\+//) {
-            $metaclass->clone_parent($meta, $name, @_);
-        }
-        else {
-            $metaclass->create($meta, $name, @_);
-        }
-    }
+    $meta->add_attribute(@_);
 }
 
 sub before {
index 07b54e7..8e89567 100644 (file)
@@ -98,9 +98,35 @@ sub get_all_method_names {
 
 sub add_attribute {
     my $self = shift;
-    my $attr = shift;
 
-    $self->{'attributes'}{$attr->name} = $attr;
+    if (@_ == 1 && blessed($_[0])) {
+        my $attr = shift @_;
+        $self->{'attributes'}{$attr->name} = $attr;
+    } else {
+        my $names = shift @_;
+        $names = [$names] if !ref($names);
+        my $metaclass = 'Mouse::Meta::Attribute';
+        my %options = @_;
+
+        if ( my $metaclass_name = delete $options{metaclass} ) {
+            my $new_class = Mouse::Util::resolve_metaclass_alias(
+                'Attribute',
+                $metaclass_name
+            );
+            if ( $metaclass ne $new_class ) {
+                $metaclass = $new_class;
+            }
+        }
+
+        for my $name (@$names) {
+            if ($name =~ s/^\+//) {
+                $metaclass->clone_parent($self, $name, @_);
+            }
+            else {
+                $metaclass->create($self, $name, @_);
+            }
+        }
+    }
 }
 
 sub compute_all_applicable_attributes {
@@ -351,7 +377,7 @@ Returns the name of the owner class.
 
 Gets (or sets) the list of superclasses of the owner class.
 
-=head2 add_attribute Mouse::Meta::Attribute
+=head2 add_attribute (Mouse::Meta::Attribute| name => spec)
 
 Begins keeping track of the existing L<Mouse::Meta::Attribute> for the owner
 class.
diff --git a/t/046-meta-add_attribute.t b/t/046-meta-add_attribute.t
new file mode 100644 (file)
index 0000000..67ce344
--- /dev/null
@@ -0,0 +1,17 @@
+use strict;
+use warnings;
+use Test::More tests => 1;
+
+{
+    package Foo;
+    use Mouse;
+}
+Foo->meta->add_attribute(
+    'foo' => (
+        is => 'ro',
+        isa => 'Str',
+        default => 'bar',
+    )
+);
+is(Foo->new->foo, 'bar');