Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

delegate Moose accessors to a HASH?

by perl5ever (Pilgrim)
on Jun 23, 2011 at 19:11 UTC ( [id://911135]=perlquestion: print w/replies, xml ) Need Help??

perl5ever has asked for the wisdom of the Perl Monks concerning the following question:

Suppose I have an object with an instance variable 'data'.
package Foo; use Moose; has data (is => 'rw');

The 'data' field is meant to populated with a hash ref.

Is is possible to delegate some accessors of Foo to the 'data' hash ref. E.g.:

my $foo = Foo->new(data => { this => 1, that => 2 }); $foo->this # returns $foo->data->{this} $foo->that(10) # sets $foo->data->{that} = 10
The delegated fields will be known in advance.

It seems that Moose::Meta::Attribute::Native is somewhat relevant here, but I don't see how it would be done.

Replies are listed 'Best First'.
Re: delegate Moose accessors to a HASH?
by ikegami (Patriarch) on Jun 23, 2011 at 19:26 UTC
    handles => { this => sub { $_[0]->data->{this} }, that => sub { $_[0]->data->{that} }, },
      The setter doesn't seem to work:
      $foo->that(10) # sets $foo->data->{that} = 10

      I can make this work:

      $foo->that = 10
      by adding :lvalue to the sub declarations, but that's not what I want.

        Sorry, I wrote it as a getter, not an accessor.

        handles => { this => sub { @_ == 1 ? $_[0]->data->{this} : $_[0]->data->{this} = $_[1] }, that => sub { @_ == 1 ? $_[0]->data->{that} : $_[0]->data->{that} = $_[1] }, },

        You can use a map to avoid duplication and/or an accessor generating function.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://911135]
Approved by BrowserUk
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (4)
As of 2024-07-17 20:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.