summaryrefslogtreecommitdiffstats
path: root/lib/MooseX/Bread/Board/Role/Service.pm
blob: 5e06eee05449876962fc1ed50ad699b363f51676 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package MooseX::Bread::Board::Role::Service;
use Moose::Role;

has associated_attribute => (
    is       => 'ro',
    isa      => 'Class::MOP::Attribute',
    required => 1,
    weak_ref => 1,
);

around get => sub {
    my $orig = shift;
    my $self = shift;

    my $container = $self->parent_container;

    if ($self->associated_attribute->has_value($container)) {
        return $self->associated_attribute->get_value($container);
    }

    return $self->$orig(@_);
};

sub parent_container {
    my $self = shift;

    my $container = $self;
    until (!defined($container)
        || ($container->isa('Bread::Board::Container')
            && $container->does('MooseX::Bread::Board::Role::Object'))) {
        $container = $container->parent;
    }
    die "Couldn't find associated object!" unless defined $container;

    return $container;
}

no Moose::Role;

1;