in reply to Role::Tiny: When to use apply_roles_to_object?

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.

Replies are listed 'Best First'.
Re^2: Role::Tiny: When to use apply_roles_to_object?
by karlgoethebier (Abbot) on May 02, 2019 at 16:55 UTC

    It really helps. Thank you and best regards, Karl

    «The Crux of the Biscuit is the Apostrophe»

    perl -MCrypt::CBC -E 'say Crypt::CBC->new(-key=>'kgb',-cipher=>"Blowfish")->decrypt_hex($ENV{KARL});'Help