Re: setting default behavior

[email protected] (Demian Riccardi)
Newsgroups perl.moose
Message-ID <CACaGo3O8D9M7m+2N4WChxDKLSZQ-YBvMJdR8E1t5eaAsyzaqxA@mail.gmail.com>
I think I figured out something (pasted below) that should be close enough
for now.

I push ifoo into ibar and created a handle, allowed default setting of bars
inside Bar, and set up a current bar (cbar) method to get the behavior I'm
looking for.

for setting first entry at object construction:
my $a = Foo->new( foos=> Bar->new( bars=>[[0,0,0]] ) );

which is about as ugly as I am!

let me know if there are cleverer ways to do this.

Thanks

Demian





{
  package Foo;
  use namespace::autoclean;
  use Moose;

  has 'foos' => (
                    is      => 'rw',
                    isa     => 'Bar',
                    handles => {
                                add_foos => 'add_bars',
                                get_foos => 'get_bars',
                                set_foos => 'set_bars',
                              count_foos => 'count_bars',
                              cfoo       => 'cbar',
                              ifoo       => 'ibar',
                               },
                    builder  => '_build_foo',
                    lazy     => 1,
                 );

  sub _build_foo{
    return Bar->new();
  }

  __PACKAGE__->meta->make_immutable;
}

{
  package Bar;
  use namespace::autoclean;
  use Moose;

  has 'ibar'  =>  (
                    is       => 'rw',
                    isa      => 'Int',
                    default  => 0,
                  );

  has 'bars'  =>  (
                    traits   => [ 'Array' ],
                    is       => 'rw',
                    isa      => 'ArrayRef',
                    default  =>  sub{[]},
                    handles  =>
                      {
                        add_bars => 'push',
                        get_bars => 'get',
                        set_bars => 'set',
                        all_bars => 'elements',
                      count_bars => 'count',
                      },
                   );

  sub cbar {
    my $self = shift;
    if (@_ == 1 && ref($_[0]) eq 'ARRAY' ){
      $self->set_bars($self->ibar, $_[0] );
    }
    else {
      return $self->get_bars( $self->ibar );
    }
  }

  __PACKAGE__->meta->make_immutable;

}

use Modern::Perl;

my $a = Foo->new(foos=> Bar->new(bars=>[[0,0,0]]));

$a->add_foos([1,1,1]);
$a->add_foos([2,2,2]);

my $aa = $a->get_foos(0);
my $bb = $a->cfoo();

$a->ifoo(2);

my $cc = $a->cfoo();
$a->cfoo([0,1,2]);

use Data::Dumper;

print Dumper $aa;
print Dumper $bb;
print Dumper $cc;
print Dumper $a->cfoo();

1;
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.