| 1 | package MooseX::Meta::Attribute::Index; | ||
| 2 | |||
| 3 | our $VERSION = 0.04; | ||
| 4 | our $AUTHORITY = 'cpan:CTBROWN'; | ||
| 5 | |||
| 6 | use Moose::Role; | ||
| 7 | use Carp; | ||
| 8 | |||
| 9 | |||
| 10 | # Given the name of the attribute return the attributes index | ||
| 11 | sub get_attribute_index { | ||
| 12 | |||
| 13 | my $self = shift; | ||
| 14 | my $name = shift; | ||
| 15 | |||
| 16 | $self->meta->get_attribute( $name )->index | ||
| 17 | |||
| 18 | } | ||
| 19 | |||
| 20 | |||
| 21 | |||
| 22 | # Given the index of the attribute return the attributes value | ||
| 23 | sub get_attribute_by_index { | ||
| 24 | |||
| 25 | my ($self, $index) = @_; | ||
| 26 | confess( "You cannot retrieve non integer valued indexes. ($index)" ) | ||
| 27 | if ( $index =~ /\D/ ); | ||
| 28 | |||
| 29 | my $attr = $self->get_attribute_name_by_index( $index ); | ||
| 30 | |||
| 31 | if ( $attr ) { | ||
| 32 | return $self->meta->get_attribute( $attr ); | ||
| 33 | } else { | ||
| 34 | carp( "There is no attribute with index, $index" ); | ||
| 35 | return undef; | ||
| 36 | } | ||
| 37 | |||
| 38 | } | ||
| 39 | |||
| 40 | |||
| 41 | |||
| 42 | # Given the index, return attribute name | ||
| 43 | sub get_attribute_name_by_index { | ||
| 44 | |||
| 45 | my ($self, $index) = @_; | ||
| 46 | # print "===>$index\t"; | ||
| 47 | confess( "You cannot retrieve non integer valued indexes. ($index)" ) | ||
| 48 | if ( $index =~ /\D/ ); | ||
| 49 | |||
| 50 | foreach my $name ( keys %{ $self->meta->get_attribute_map } ) { | ||
| 51 | my $attribute = $self->meta->get_attribute( $name ); | ||
| 52 | return ( $name ) | ||
| 53 | if ( $attribute->can('index') and $attribute->index == $index ); | ||
| 54 | } | ||
| 55 | |||
| 56 | carp( "There is no attribute with index, $index" ); | ||
| 57 | return undef; | ||
| 58 | |||
| 59 | } | ||
| 60 | |||
| 61 | |||
| 62 | |||
| 63 | package MooseX::Meta::Attribute::Trait::Index; | ||
| 64 | |||
| 65 | use Moose::Role; | ||
| 66 | |||
| 67 | has index => ( | ||
| 68 | is => 'rw' , | ||
| 69 | isa => 'Int' , | ||
| 70 | predicate => 'has_index' , | ||
| 71 | trigger => sub { | ||
| 72 | my ( $self, $value, $meta ) = @_ ; | ||
| 73 | if ( $value < 0 ) { | ||
| 74 | confess( "A negative value cannot be used as an " . | ||
| 75 | "index for an attribute.\n" ); | ||
| 76 | } | ||
| 77 | } , | ||
| 78 | ); | ||
| 79 | |||
| 80 | |||
| 81 | package Moose::Meta::Attribute::Custom::Trait::Index; | ||
| 82 | sub register_implementation { | ||
| 83 | 'MooseX::Meta::Attribute::Trait::Index' | ||
| 84 | }; | ||
| 85 | |||
| 86 | |||
| 87 | |||
| 88 | |||
| 89 | 1; | ||
| 90 | |||
| 91 | |||
| 92 | __END__ |