Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re^6: Moose and default values

by tobyink (Abbot)
on Feb 20, 2013 at 22:54 UTC ( #1019859=note: print w/ replies, xml ) Need Help??


in reply to Re^5: Moose and default values
in thread Moose and default values

Maybe something along the lines of:

around BUILDARGS => sub { my $orig = shift; my $self = shift; my $params = $self->$orig(@_); $params->{$_} || delete $params->{$_} for qw/ foo bar /; return $params; };

This will discard false parameters for the "foo" and "bar" attributes.

package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name


Comment on Re^6: Moose and default values
Download Code
Re^7: Moose and default values
by morgon (Deacon) on Feb 20, 2013 at 23:02 UTC
    Sure you can always hack togther something, I was more looking for a way to do such things declaratively...

    But your Haskell-ripoff is a at least a step forward - thanks.

      With enough hacking you can make anything look declarative!

      use v5.14; use strict; use warnings; # Ugly hack code # package MooseX::AttributeShouldIgnoreFalse { BEGIN { $INC{'MooseX/AttributeShouldIgnoreFalse.pm'} = __FILE__ }; use Sub::Exporter -setup => { exports => ['attribute_should_ignore_false'], groups => { default => ['attribute_should_ignore_false'], }, }; sub attribute_should_ignore_false { my @attrs = @_; my $meta = (scalar caller)->meta; $meta->add_around_method_modifier(BUILDARGS => sub { my $orig = shift; my $self = shift; my $parm = $self->$orig(@_); $parm->{$_} || delete $parm->{$_} for @attrs; $parm; }); } } # Lovely declarative code # package Foo { use Moose; use MooseX::AttributeShouldIgnoreFalse; has foo => (is => 'ro', default => 'whatever'); attribute_should_ignore_false 'foo'; } my $value = 'hello'; print Foo->new(foo => $value)->dump; $value = ''; print Foo->new(foo => $value)->dump;
      package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name
        Were getting here :-)

        Ideally I would want to declare everything at the attriute-level, e.g.:

        has foo => (is => "ro", default => { value => "whatever", when => "fal +se" });
        Can you do that as well?

        I am not so much interested in the feature itself, but it is interesting to see some examples of Moose-metaprogramming at work...

        Thanks!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1019859]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (6)
As of 2014-08-23 08:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (172 votes), past polls