From: Graham Knop Date: Wed, 10 Jul 2013 18:15:46 +0000 (-0400) Subject: apply default values when applying role to object X-Git-Tag: v1.003000~21 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=fe0d87fb8d5ec93bf32a1c256c2107262f04ce0f;p=gitmo%2FMoo.git apply default values when applying role to object --- diff --git a/lib/Moo/Role.pm b/lib/Moo/Role.pm index 0f93a78..764ffb2 100644 --- a/lib/Moo/Role.pm +++ b/lib/Moo/Role.pm @@ -262,6 +262,37 @@ sub create_class_with_roles { return $new_name; } +sub apply_roles_to_object { + my ($me, $object, @roles) = @_; + my $new = $me->SUPER::apply_roles_to_object($object, @roles); + if ($INC{'Moo.pm'} + and my $m = Moo->_accessor_maker_for(ref $new) + and my $con_gen = Moo->_constructor_maker_for(ref $new)) { + require Sub::Quote; + + my $specs = $con_gen->all_attribute_specs; + my %attrs = map { @{$INFO{$_}{attributes}||[]} } @roles; + + my $assign = ''; + my %captures; + foreach my $name ( keys %attrs ) { + my $spec = $specs->{$name}; + if ($m->has_eager_default($name, $spec)) { + my ($has, $has_cap) + = $m->generate_simple_has('$_[0]', $name, $spec); + my ($code, $pop_cap) + = $m->generate_use_default('$_[0]', $name, $spec, $has); + + $assign .= $code; + @captures{keys %$has_cap, keys %$pop_cap} + = (values %$has_cap, values %$pop_cap); + } + } + Sub::Quote::quote_sub($assign, \%captures)->($new); + } + return $new; +} + sub _composable_package_for { my ($self, $role) = @_; my $composed_name = 'Role::Tiny::_COMPOSABLE::'.$role;