From 2674cfd2e9ff7a8b4f2952a5f84e94804afc3a1f Mon Sep 17 00:00:00 2001 From: Jesse Luehrs Date: Sat, 29 Dec 2012 01:06:47 -0600 Subject: add a bit more api to the singleton instance --- lib/Bread/Board.pm | 9 ++++-- t/030_lifecycle_singleton.t | 72 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+), 2 deletions(-) create mode 100644 t/030_lifecycle_singleton.t diff --git a/lib/Bread/Board.pm b/lib/Bread/Board.pm index 82b886c..c741757 100644 --- a/lib/Bread/Board.pm +++ b/lib/Bread/Board.pm @@ -406,15 +406,20 @@ class Container does Traversable { role Singleton does Lifecycle is export { has $!instance; - has Bool $!has_instance; + has Bool $.has_instance; method get { - if !$!has_instance { + if !$.has_instance { $!instance = callsame; $!has_instance = True; } return $!instance; } + + method flush_instance { + $!instance = Any; + $!has_instance = False; + } } our $CC; diff --git a/t/030_lifecycle_singleton.t b/t/030_lifecycle_singleton.t new file mode 100644 index 0000000..9da7b83 --- /dev/null +++ b/t/030_lifecycle_singleton.t @@ -0,0 +1,72 @@ +use v6; +use Test; + +use Bread::Board; + +# PERL6: doing anything at all with the type object for a role with required +# methods is broken +#sub does_ok(Mu $var, Mu $type, $msg = ("The object does '" ~ $type.perl ~ "'")) { +sub does_ok(Mu $var, Mu $type, $msg = ("The object does [some role]")) { + ok($var.does($type), $msg); +} + +class Needle { } +class Mexican::Black::Tar { } +class Addict { + has ($.needle, $.spoon, $.stash); +} + +my $s = Bread::Board::ConstructorInjection.new( + lifecycle => Singleton, + name => 'William', + class => Addict, + dependencies => { + needle => Bread::Board::ConstructorInjection.new( + name => 'spike', + class => Needle, + ), + spoon => Bread::Board::Literal.new( + name => 'works', + value => 'Spoon!', + ), + }, + parameters => { + stash => { isa => Mexican::Black::Tar }, + }, +); + +isa_ok($s, Bread::Board::ConstructorInjection); +does_ok($s, Bread::Board::Service); + +does_ok($s, Bread::Board::Singleton); +is($s.lifecycle.^name, 'Singleton'); + +ok(!$s.has_instance); +my $i = $s.get(stash => Mexican::Black::Tar.new); +ok($s.has_instance); + +isa_ok($i, Addict); +isa_ok($i.needle, Needle); +is($i.spoon, 'Spoon!'); +isa_ok($i.stash, Mexican::Black::Tar); + +{ + my $i2 = $s.get(stash => Mexican::Black::Tar.new); + is($i, $i2); +} + +$s.flush_instance; + +{ + my $i2 = $s.get(stash => Mexican::Black::Tar.new); + isnt($i, $i2); + + { + my $i2a = $s.get(stash => Mexican::Black::Tar.new); + is($i2, $i2a); + } +} + +done; + +# vim:ft=perl6:foldmethod=manual -- cgit v1.2.3