develooper Front page | perl.moose | Postings from February 2018

Re: Setting delegated attributes in constructors

Thread Previous
From:
Nick Perez
Date:
February 13, 2018 14:38
Subject:
Re: Setting delegated attributes in constructors
Message ID:
20180213153758.7aa3511b@nicklaptop.localdomain
Delegated methods are typically used as a convenience technique to
class composition to avoid writing your own wrapper methods that call
the underlying methods the contained object has. It really wasn't
intended to subvert inheritance like you're trying to do.

HTH,
Nick




On Tue, 13 Feb 2018 10:17:19 +0000
Merlyn Kline <merlyn@binary.co.uk> wrote:

> I'd like to set delegated attributes in my object constructors (e.g.
> as below)  but this doesn't seem to work. Am I missing something?
> 
> Merlyn
> 
> 
> #!/usr/bin/perl
> 
> package SubClass;
> 
> use Moose;
> 
> has thing => ( is => 'rw', isa => 'Int' );
> 
> before thing => sub {
>     shift;
>     print "subthing: ", @_ ? 'set to ' . (shift // '<undef>') :
> '(read)', "\n";
>     return;
> };
> 
> 
> package Class;
> 
> use Moose;
> 
> has sub_object => ( is => 'rw', isa => 'SubClass', handles =>
> ['thing'], builder => '_build_sub_object' );
> #has sub_object => ( is => 'rw', isa => 'SubClass', handles =>
> ['thing'], default => sub { _build_sub_object(); } );
> 
> sub _build_sub_object {
>     my $self = shift;
> 
>     print "_build_sub_object\n";
>     return SubClass->new;
> }
> 
> 
> package main;
> 
> use strict;
> use warnings;
> 
> print "Start\n";
> my $object = Class->new(thing => 1);
> print "Built\n";
> 
> print "Thing 1 = ", ($object->thing // '<undef>'), "\n";
> 
> $object->thing(2);
> 
> print "Thing 2 = ", ($object->thing // '<undef>'), "\n";
> 

Thread Previous


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About