File Coverage

blib/lib/MooseX/Iterator/Meta/Iterable.pm
Criterion Covered Total %
statement 1 3 33.3
branch n/a
condition n/a
subroutine 1 1 100.0
pod n/a
total 2 4 50.0


line stmt bran cond sub pod time code
1             package MooseX::Iterator::Meta::Iterable;
2 1     1   1873 use Moose;
  0            
  0            
3             use MooseX::Iterator::Array;
4              
5             use Carp 'confess';
6              
7             our $VERSION = '0.11';
8             our $AUTHORITY = 'cpan:RLB';
9              
10             extends 'Moose::Meta::Attribute';
11              
12             has iterate_over => ( is => 'ro', isa => 'Str', default => '' );
13              
14             before '_process_options' => sub {
15             my ( $class, $name, $options ) = @_;
16              
17             #if ( defined $options->{is} ) {
18             # confess "Can not use 'is' with the Iterable metaclass";
19             #}
20             $options->{is} = 'bare';
21             $class->meta->add_attribute( iterate_name => ( is => 'ro', isa => 'Str', default => $name ) );
22             };
23              
24             after 'install_accessors' => sub {
25             my ($self) = @_;
26             my $class = $self->associated_class;
27              
28             my $iterate_name = $self->iterate_name;
29             my $collection_name = $self->iterate_over;
30              
31             my $type = $class->get_attribute($collection_name)->type_constraint->name;
32             my $collection = $class->get_attribute($collection_name)->get_read_method;
33              
34             my $iterator_class_name = $self->_calculate_iterator_class_for_type($type);
35              
36             confess "Invalid iterator class given" if !$iterator_class_name;
37             confess "$iterator_class_name does not implement MooseX::Iterator::Role" if !$iterator_class_name->does('MooseX::Iterator::Role');
38              
39             $class->add_method(
40             $iterate_name => sub {
41             my ($self) = @_;
42             $iterator_class_name->new( collection => $self->$collection );
43             }
44             );
45             };
46              
47             sub _calculate_iterator_class_for_type {
48             my ( $self, $type ) = @_;
49              
50             if ( $type eq 'ArrayRef' ) {
51             return 'MooseX::Iterator::Array';
52             }
53             elsif ( $type eq 'HashRef' ) {
54             return 'MooseX::Iterator::Hash';
55             }
56             }
57              
58             no Moose;
59              
60             package Moose::Meta::Attribute::Custom::Iterable;
61             sub register_implementation { 'MooseX::Iterator::Meta::Iterable' }
62              
63             1;