1 package Mouse::Meta::Attribute;
2 use Mouse::Util qw(:meta); # enables strict and warnings
6 use Mouse::Meta::TypeConstraint;
8 my %valid_options = map { $_ => undef } (
37 # Moose defines, but Mouse doesn't
38 #'definition_context',
42 # special case for AttributeHelpers
47 our @CARP_NOT = qw(Mouse::Meta::Class);
53 my $args = $class->Mouse::Object::BUILDARGS(@_);
55 # XXX: for backward compatibility (with method modifiers)
56 if($class->can('canonicalize_args') != \&canonicalize_args){
57 %{$args} = $class->canonicalize_args($name, %{$args});
60 $class->_process_options($name, $args);
62 $args->{name} = $name;
66 my @bad = grep{ !exists $valid_options{$_} } keys %{$args};
68 # (2) known by subclasses
69 if(@bad && $class ne __PACKAGE__){
73 map { $_->init_arg() }
74 $class->meta->get_all_attributes()
76 @bad = grep{ !exists $valid_attrs{$_} } @bad;
79 # (3) bad options found
82 "Found unknown argument(s) passed to '$name' attribute constructor in '$class': "
83 . Mouse::Util::english_list(@bad));
86 my $self = bless $args, $class;
89 if($class ne __PACKAGE__){
90 $class->meta->_initialize_object($self, $args);
96 sub has_read_method { $_[0]->has_reader || $_[0]->has_accessor }
97 sub has_write_method { $_[0]->has_writer || $_[0]->has_accessor }
99 sub _create_args { # DEPRECATED
100 $_[0]->{_create_args} = $_[1] if @_ > 1;
101 $_[0]->{_create_args}
104 sub interpolate_class{
105 my($class, $args) = @_;
107 if(my $metaclass = delete $args->{metaclass}){
108 $class = Mouse::Util::resolve_metaclass_alias( Attribute => $metaclass );
112 if(my $traits_ref = delete $args->{traits}){
114 for (my $i = 0; $i < @{$traits_ref}; $i++) {
115 my $trait = Mouse::Util::resolve_metaclass_alias(Attribute => $traits_ref->[$i], trait => 1);
117 next if $class->does($trait);
119 push @traits, $trait;
122 push @traits, $traits_ref->[++$i]
123 if ref($traits_ref->[$i+1]);
127 $class = Mouse::Meta::Class->create_anon_class(
128 superclasses => [ $class ],
135 return( $class, @traits );
138 sub canonicalize_args{ # DEPRECATED
139 #my($self, $name, %args) = @_;
140 my($self, undef, %args) = @_;
142 Carp::cluck("$self->canonicalize_args has been deprecated."
143 . "Use \$self->_process_options instead.");
148 sub create { # DEPRECATED
149 #my($self, $class, $name, %args) = @_;
152 Carp::cluck("$self->create has been deprecated."
153 . "Use \$meta->add_attribute and \$attr->install_accessors instead.");
159 sub _coerce_and_verify {
160 #my($self, $value, $instance) = @_;
161 my($self, $value) = @_;
163 my $type_constraint = $self->{type_constraint};
164 return $value if !defined $type_constraint;
166 if ($self->should_coerce && $type_constraint->has_coercion) {
167 $value = $type_constraint->coerce($value);
170 $self->verify_against_type_constraint($value);
175 sub verify_against_type_constraint {
176 my ($self, $value) = @_;
178 my $type_constraint = $self->{type_constraint};
179 return 1 if !$type_constraint;
180 return 1 if $type_constraint->check($value);
182 $self->_throw_type_constraint_error($value, $type_constraint);
185 sub _throw_type_constraint_error {
186 my($self, $value, $type) = @_;
189 sprintf q{Attribute (%s) does not pass the type constraint because: %s},
191 $type->get_message($value),
195 sub clone_and_inherit_options{
197 my $args = $self->Mouse::Object::BUILDARGS(@_);
199 my($attribute_class, @traits) = ref($self)->interpolate_class($args);
201 $args->{traits} = \@traits if @traits;
202 # do not inherit the 'handles' attribute
203 foreach my $name(keys %{$self}){
204 if(!exists $args->{$name} && $name ne 'handles'){
205 $args->{$name} = $self->{$name};
209 # remove temporary caches
210 foreach my $attr(keys %{$args}){
211 if($attr =~ /\A _/xms){
212 delete $args->{$attr};
216 return $attribute_class->new($self->name, $args);
219 sub clone_parent { # DEPRECATED
223 my %args = ($self->get_parent_args($class, $name), @_);
225 Carp::cluck("$self->clone_parent has been deprecated."
226 . "Use \$meta->add_attribute and \$attr->install_accessors instead.");
228 $self->clone_and_inherited_args($class, $name, %args);
231 sub get_parent_args { # DEPRECATED
236 for my $super ($class->linearized_isa) {
237 my $super_attr = $super->can("meta") && $super->meta->get_attribute($name)
239 return %{ $super_attr->_create_args };
242 $self->throw_error("Could not find an attribute by the name of '$name' to inherit from");
246 sub get_read_method {
247 return $_[0]->reader || $_[0]->accessor
249 sub get_write_method {
250 return $_[0]->writer || $_[0]->accessor
253 sub _get_accessor_method_ref {
254 my($self, $type, $generator) = @_;
256 my $metaclass = $self->associated_class
257 || $self->throw_error('No asocciated class for ' . $self->name);
259 my $accessor = $self->$type();
261 return $metaclass->get_method_body($accessor);
264 return $self->accessor_metaclass->$generator($self, $metaclass);
268 sub get_read_method_ref{
270 return $self->{_read_method_ref} ||= $self->_get_accessor_method_ref('get_read_method', '_generate_reader');
273 sub get_write_method_ref{
275 return $self->{_write_method_ref} ||= $self->_get_accessor_method_ref('get_write_method', '_generate_writer');
279 my($self, $object, $value) = @_;
280 return $self->get_write_method_ref()->($object, $value);
284 my($self, $object) = @_;
285 return $self->get_read_method_ref()->($object);
289 my($self, $object) = @_;
290 my $accessor_ref = $self->{_predicate_ref}
291 ||= $self->_get_accessor_method_ref('predicate', '_generate_predicate');
293 return $accessor_ref->($object);
297 my($self, $object) = @_;
298 my $accessor_ref = $self->{_crealer_ref}
299 ||= $self->_get_accessor_method_ref('clearer', '_generate_clearer');
301 return $accessor_ref->($object);
305 sub associate_method{
306 #my($attribute, $method_name) = @_;
308 $attribute->{associated_methods}++;
312 sub install_accessors{
315 my $metaclass = $attribute->associated_class;
316 my $accessor_class = $attribute->accessor_metaclass;
318 foreach my $type(qw(accessor reader writer predicate clearer)){
319 if(exists $attribute->{$type}){
320 my $generator = '_generate_' . $type;
321 my $code = $accessor_class->$generator($attribute, $metaclass);
322 $metaclass->add_method($attribute->{$type} => $code);
323 $attribute->associate_method($attribute->{$type});
328 if(exists $attribute->{handles}){
329 my %handles = $attribute->_canonicalize_handles($attribute->{handles});
331 while(my($handle, $method_to_call) = each %handles){
332 $metaclass->add_method($handle =>
333 $attribute->_make_delegation_method(
334 $handle, $method_to_call));
336 $attribute->associate_method($handle);
340 if($attribute->can('create') != \&create){
341 # backword compatibility
342 $attribute->create($metaclass, $attribute->name, %{$attribute});
348 sub delegation_metaclass() { ## no critic
349 'Mouse::Meta::Method::Delegation'
352 sub _canonicalize_handles {
353 my($self, $handles) = @_;
355 if (ref($handles) eq 'HASH') {
358 elsif (ref($handles) eq 'ARRAY') {
359 return map { $_ => $_ } @$handles;
361 elsif ( ref($handles) eq 'CODE' ) {
362 my $class_or_role = ( $self->{isa} || $self->{does} )
363 || $self->throw_error( "Cannot find delegate metaclass for attribute " . $self->name );
364 return $handles->( $self, Mouse::Meta::Class->initialize("$class_or_role"));
366 elsif (ref($handles) eq 'Regexp') {
367 my $class_or_role = ($self->{isa} || $self->{does})
368 || $self->throw_error("Cannot delegate methods based on a Regexp without a type constraint (isa)");
370 my $meta = Mouse::Meta::Class->initialize("$class_or_role"); # "" for stringify
371 return map { $_ => $_ }
372 grep { !Mouse::Object->can($_) && $_ =~ $handles }
373 Mouse::Util::is_a_metarole($meta)
374 ? $meta->get_method_list
375 : $meta->get_all_method_names;
378 $self->throw_error("Unable to canonicalize the 'handles' option with $handles");
382 sub _make_delegation_method {
383 my($self, $handle, $method_to_call) = @_;
384 return Mouse::Util::load_class($self->delegation_metaclass)
385 ->_generate_delegation($self, $handle, $method_to_call);
391 my $metaclass = (ref $self && $self->associated_class) || 'Mouse::Meta::Class';
392 $metaclass->throw_error(@_, depth => 1);
400 Mouse::Meta::Attribute - The Mouse attribute metaclass
404 This document describes Mouse version 0.50_09
408 =head2 C<< new(%options) -> Mouse::Meta::Attribute >>
410 Instantiates a new Mouse::Meta::Attribute. Does nothing else.
412 It adds the following options to the constructor:
416 =item C<< is => 'ro', 'rw', 'bare' >>
418 This provides a shorthand for specifying the C<reader>, C<writer>, or
419 C<accessor> names. If the attribute is read-only ('ro') then it will
420 have a C<reader> method with the same attribute as the name.
422 If it is read-write ('rw') then it will have an C<accessor> method
423 with the same name. If you provide an explicit C<writer> for a
424 read-write attribute, then you will have a C<reader> with the same
425 name as the attribute, and a C<writer> with the name you provided.
427 Use 'bare' when you are deliberately not installing any methods
428 (accessor, reader, etc.) associated with this attribute; otherwise,
429 Moose will issue a deprecation warning when this attribute is added to a
432 =item C<< isa => Type >>
434 This option accepts a type. The type can be a string, which should be
435 a type name. If the type name is unknown, it is assumed to be a class
438 This option can also accept a L<Moose::Meta::TypeConstraint> object.
440 If you I<also> provide a C<does> option, then your C<isa> option must
441 be a class name, and that class must do the role specified with
444 =item C<< does => Role >>
446 This is short-hand for saying that the attribute's type must be an
447 object which does the named role.
449 B<This option is not yet supported.>
451 =item C<< coerce => Bool >>
453 This option is only valid for objects with a type constraint
454 (C<isa>). If this is true, then coercions will be applied whenever
455 this attribute is set.
457 You can make both this and the C<weak_ref> option true.
459 =item C<< trigger => CodeRef >>
461 This option accepts a subroutine reference, which will be called after
462 the attribute is set.
464 =item C<< required => Bool >>
466 An attribute which is required must be provided to the constructor. An
467 attribute which is required can also have a C<default> or C<builder>,
468 which will satisfy its required-ness.
470 A required attribute must have a C<default>, C<builder> or a
471 non-C<undef> C<init_arg>
473 =item C<< lazy => Bool >>
475 A lazy attribute must have a C<default> or C<builder>. When an
476 attribute is lazy, the default value will not be calculated until the
479 =item C<< weak_ref => Bool >>
481 If this is true, the attribute's value will be stored as a weak
484 =item C<< auto_deref => Bool >>
486 If this is true, then the reader will dereference the value when it is
487 called. The attribute must have a type constraint which defines the
488 attribute as an array or hash reference.
490 =item C<< lazy_build => Bool >>
492 Setting this to true makes the attribute lazy and provides a number of
500 is equivalent to this:
505 builder => '_build_size',
506 clearer => 'clear_size',
507 predicate => 'has_size',
512 =head2 C<< associate_method(MethodName) >>
514 Associates a method with the attribute. Typically, this is called internally
515 when an attribute generates its accessors.
517 Currently the argument I<MethodName> is ignored in Mouse.
519 =head2 C<< verify_against_type_constraint(Item) -> TRUE | ERROR >>
521 Checks that the given value passes this attribute's type constraint. Returns C<true>
522 on success, otherwise C<confess>es.
524 =head2 C<< clone_and_inherit_options(options) -> Mouse::Meta::Attribute >>
526 Creates a new attribute in the owner class, inheriting options from parent classes.
527 Accessors and helper methods are installed. Some error checking is done.
529 =head2 C<< get_read_method_ref >>
531 =head2 C<< get_write_method_ref >>
533 Returns the subroutine reference of a method suitable for reading or
534 writing the attribute's value in the associated class. These methods
535 always return a subroutine reference, regardless of whether or not the
536 attribute is read- or write-only.
540 L<Moose::Meta::Attribute>
542 L<Class::MOP::Attribute>