I have a Moose
class, that is consuming a Role like ...
package MyPackage;
use Moose;
with 'MyRole';
# ...
__PACKAGE__->meta->make_immutable;
My goal is, to only use a role, when another module is installed on the running system without creating a new dependency in my modules. When the module is not available the normal package functionality should be used, without the role and without crashing.
I already found ensure_all_roles
and apply_all_roles
in Moose::Util. I tried to write a method, that calls them when my conditions are fulfilled. But since I want my class to be immutable, the application crashes...
The 'add_package_symbol' method cannot be called on an immutable instance
That makes sense to me.
My question is: How to apply a role under a given condition for a class, that is marked as immutable?
I tried the following
with 'MyRole' if $condition;
It works without errors for both truth values of $condition.