default/replacable values in Bread::Board

211 views Asked by At

I found myself instantiating the same objects in numerous tests, so I'm trying to replace this constant setup by using Bread::Board. Most of the time I will want the dependencies to have the same configuration. But occasionally I may want to have an instance created with parameters that are not the default. I'd also like to be able to change this after I've created an instance of the container. e.g. I'd normally want

my $c = Test::Container->new;

my $bar = $c->resolve( service => 'bar' ); # where bar depends on foo

but sometimes what I really need is something like

my $bar = $c->resolve( service => 'bar', {
              services => {
                foo => { init => 'arg' }
              }
          }

so that service foo is initialized differently while creating the instance of bar.

1

There are 1 answers

0
xenoterracide On BEST ANSWER

This was provided to me by Jesse Luehrs (Doy) on #moose and appears that it'll do what I want.

#!/usr/bin/env perl
use v5.14;
use strict;
use warnings;

package Container {
use Moose;
use Bread::Board;

extends 'Bread::Board::Container';

has '+name' => (default => 'Container');

sub BUILD {
    my $self = shift;
    container $self => as {
        service foo => (
            block => sub {
                my $s = shift;
                $s->param('foo_val');
            },
            parameters => {
                foo_val => { isa => 'Str' },
            },
        );
        service bar => (
            block => sub {
                my $s = shift;
                $s->param('foo')->inflate(foo_val => $s->param('foo_val')) . 'BAR';
            },
            dependencies => ['foo'],
            parameters => {
                foo_val => { isa => 'Str', default => 'FOO' },
            },
        );
    };
}
}

my $c = Container->new;
warn $c->resolve(service => 'bar');
warn $c->resolve(service => 'bar', parameters => { foo_val => 'baz' });