Access MooseX :: ClassAttribute in Moose :: Role

Here is the puzzle. I use Moose :: Role as an interface where specific classes need to implement the necessary attributes defined by the role. The role also defines some methods that perform attribute logic. Here's a smaller version of what I'm trying to do.

package Parent;
use Moose::Role;
requires '_build_permission_level';

has 'permission_level' => (
    is => 'ro',
    isa => Int,
    lazy_build => 1,
);

use constant {
    LEVEL1 = 1,
    LEVEL2 = 2,
    LEVEL3 = 3,
};

sub can_do_action {
    my $self = shift;
    return $self->permission_level() >= LEVEL2;
}

package Child;
use Moose;
with 'Parent';

sub _build_permission_level { return Parent->LEVEL3; }

Obviously, I have many child classes with different permission levels. Now it works, except that it is terribly inefficient. All instances of Child will always have the same permission level, but I have to create an instance to ask if it can perform the action. When you run this in bulk 10,000 times, well, you get an image.

, permission_level . Moose-y. , allow_level $self.

package Parent;
use Moose::Role;
use MooseX::ClassAttribute;
requires '_build_permission_level';

class_has 'permission_level' => (
    is => 'ro',
    isa => Int,
    builder => '_build_permission_level',
);

use constant {
    LEVEL1 = 1,
    LEVEL2 = 2,
    LEVEL3 = 3,
};

sub can_do_action {
    return permission_level() >= LEVEL2;
}

package Child;
use Moose;
with 'Parent';

sub _build_permission_level { return Parent->LEVEL3; }

undefined, Parent:: permission_level. , _. ? , . - . , Parent, , Child?

+3
1

, , sub Parent::permission_level. : has class_has - ; sub , can_do_action.

, . can_do_action :

sub can_do_action {
    my ($class) = @_;

    return $class->permission_level >= LEVEL2;
}

. , Parent::permission_level.

+2

All Articles