Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

How to inject role to Caller Module?

by smarthacker67 (Beadle)
on Jun 20, 2022 at 18:08 UTC ( #11144881=perlquestion: print w/replies, xml ) Need Help??

smarthacker67 has asked for the wisdom of the Perl Monks concerning the following question:

Hello Respected Monks I am seeking some help question.
package Validation; use Moose::Role; sub check_entity { my ( $self, $db_id ) = @_; #some logic my $found_db = sub { #logic verify id present in db return 1; } return $found_db; }

I have a module that helps me write clean modules using the following `package MyApp::Moose;`. I tried searching a lot and am not sure exactly how I can inject the above role to the caller (so that it will get consumed) and the caller can have access to `check_entity` method.

I refered

Note:- I cant create an object of the caller since it has some required entity (*object may not be needed to inject role I believe)

But unfortunately, I couldn't able to figure out the right way, I am sure there must be a simple way to do it which I am missing out. Also want to do similar for multiple roles in the future once I develop them.

package MyApp::Moose; use strict; use warnings; use namespace::autoclean; use Hook::AfterRuntime; use Import::Into; use Moose (); use Clone 'clone'; sub import { my ($class, @opts) = @_; my $caller = caller; my %opt = map { $_ => 1 } @opts; strict->import::into($caller); warnings->import(); Clone->import::into($caller,'clone'); if($opt{role}) { require Moose::Role; Moose::Role->import({into=>$caller}); } else { Moose->import({into=>$caller}); after_runtime { $caller->meta->make_immutable(); }; } namespace::autoclean->import( -cleanee => $caller, ); return; } 1;

* Currently Using above in code like this.

package MyApp::Process; use MyApp::Moose; sub some_method { my ($self, $db_id) = @_; # I want to call like this $self->check_entity($db_id) || return; } 1;

I really appreciate any help you can provide.

I was hoping I could inject it directly to the caller using but after several attempts, I was unable to accomplish

The same question was Posted on StackOverflow.

Replies are listed 'Best First'.
Re: How to inject role to Caller Module?
by smarthacker67 (Beadle) on Jun 21, 2022 at 16:09 UTC
    This worked thanks @tobyink
    use Moose::Util (); Moose::Util::ensure_all_roles( $caller, 'Validation' );

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11144881]
Approved by davies
Front-paged by Corion
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2023-06-04 20:13 GMT
Find Nodes?
    Voting Booth?
    How often do you go to conferences?

    Results (22 votes). Check out past polls.