Home > database >  How to inject role to Caller Module?
How to inject role to Caller Module?

Time:06-21

  • I have Role (there will be multiple such roles)
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.

CodePudding user response:

Generally speaking, the caller should choose to import your role. They do this with the with keyword:

package MyApp::SomeClass;

use MyApp::Moose;
with 'Validation';

...;

However, if you do wish to automatically apply your role to $caller, that's pretty easy:

use Moose::Util ();
Moose::Util::ensure_all_roles( $caller, 'Validation' );
  • Related