Hi kgb,

I use that function in two ways.

  1. When building an object that needs to consume one of a selection of Roles depending on some run-time state, I often have a line that constructs the name of the Role and then composes it into the object with apply_roles_to_object.
  2. When testing a Role, it's often easier or more direct to make a simple object and compose the Role into it, as Toby said, versus having your entire framework fire up to create an object instance, eg when that might imply unrelated DB connections or whatever.

For example:

use Test::Most 'die'; use Role::Tiny; package MyClass { # standing in for the real consumer of the role, # which is expensive to instantiate in some way ... use Moo; }; package MyRole { use Moo::Role; sub foo { 42 } }; subtest 'Applying' => sub { my $o = MyClass->new; is( ref $o, 'MyClass', 'object instantiated' ); ok( Role::Tiny->apply_roles_to_object($o, 'MyRole'), 'role applied +' ); is( $o->foo, 42, 'method in Role works!' ); }; done_testing;

Hope this helps!


The way forward always starts with a minimal test.

In reply to Re: Role::Tiny: When to use apply_roles_to_object? by 1nickt
in thread Role::Tiny: When to use apply_roles_to_object? by karlgoethebier

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.