Thanks choroba, I didn't know about those Role::Tiny methods.

I am not sure about whether I prefer them to eval "with '$module'; 1;", though.

I had to load Role::Tiny explicitly not importing anything, since its before(), after(), around() and with() methods clash with Moo's :

Subroutine MyClass::before redefined at [...]/5.22.0/Role/Tiny.pm line + 58. Subroutine MyClass::after redefined at [...]/5.22.0/Role/Tiny.pm line +58. Subroutine MyClass::around redefined at [...]/5.22.0/Role/Tiny.pm line + 58. Subroutine MyClass::with redefined at [...]/5.22.0/Role/Tiny.pm line 6 +7.

And even when I do that I can't use apply_roles_to_object() inside sub BUILD, because the parent's methods haven't been loaded and thus the child's will be.

package MyClass::Child; use Moo::Role; sub foo { die 'horribly'; } sub bar { return 'bar'; } 1;
package MyClass; use Moo; use Role::Tiny(); sub BUILD { my $self = shift; Role::Tiny->apply_roles_to_object( $self, 'MyClass::Child' ); return $self; }; sub foo { return 'foo'; } 1;
Output:
$ perl -MMyClass -E '$o = MyClass->new; say $o->foo, $o->bar;' horribly at MyClass/Child.pm line 5.

So the only way I could make it work as part of the Moo constructor was with apply_roles_to_package() :

package MyClass; use Moo; use Role::Tiny(); sub BUILD { my $self = shift; Role::Tiny->apply_roles_to_package( __PACKAGE__, 'MyClass::Child' +); return $self; }; sub foo { return 'foo'; } 1;
Output:
$ perl -MMyClass -E '$o = MyClass->new; say $o->foo, $o->bar;' foobar

Thanks again for the pointer.


The way forward always starts with a minimal test.

In reply to Re^3: Is there a better way to do this? by 1nickt
in thread Is there a better way to do this? by TorontoJim

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.