Moose: How to get an array of objects? Features?

I am starting to understand that this is for beginners:

package Bad; has 'arr' => ( is => 'rw', 'ArrayRef[Str]' ); package main; my $bad = Bad->new(arr => [ "foo", "bar" ]); print $bad->arr->[0], "\n"; 

Enter the characteristics. However, the APIs are haunting me. Am I misunderstood something? Can I get this API as well?

 print $bad->arr->get(0), "\n"; 

More details

Check out an example of canonical features from Moose :: Meta :: Attribute :: Native :: Trait :: Array

 package Stuff; use Moose; has 'options' => ( traits => ['Array'], is => 'ro', isa => 'ArrayRef[Str]', default => sub { [] }, handles => { all_options => 'elements', add_option => 'push', map_options => 'map', filter_options => 'grep', find_option => 'first', get_option => 'get', join_options => 'join', count_options => 'count', has_options => 'count', has_no_options => 'is_empty', sorted_options => 'sort', }, ); no Moose; 1; 

Such an object is used, for example:

 my $option = $stuff->get_option(1); 

I really don't like this for the single array attribute that I get, and I need to manually call 11 methods in the Stuff class - one for each individual operation that can be used for "options". Inconsistent naming should happen, and it swells.

How do I (elegantly) get an API like:

 my $option = $stuff->options->get(1); 

Where are all the methods from Moose :: Meta :: Attribute :: Native :: Trait :: Array implemented in a safe type way?

Then all operations on each one array are called exactly the same ...

(I actually use Mouse, but most of Mouse is identical to Moose)

+4
source share
1 answer

I think the best way to get your API in this format is to create a new object for these options and directly pass methods to it. Sort of:

 package Stuff; use Moose; use Stuff::Options; has 'options' => ( 'is' => "ro", 'isa' => "Stuff::Options", 'default' => sub { Stuff::Options->new }, ); no Moose; 1; 

And then in Stuff/Options.pm :

 package Stuff::Options; use Moose; has '_options' => ( 'is' => "ro", 'isa' => "ArrayRef[Str]", 'traits' => [ "Array" ], 'default' => sub { [] }, 'handles' => [ qw(elements push map grep first get join count is_empty sort) ], ); no Moose; 1; 

This will allow you to use the code as in your example ( $stuff->options->get(1) ).

+5
source

All Articles