From: Shawn M Moore Date: Sun, 16 Dec 2007 14:01:01 +0000 (+0000) Subject: Do a bit of fixing. instance and new are one and the same. More tests to ensure that... X-Git-Tag: 0.09_02~30 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=1467693305140ae67c90d332344ef89d02d91fa4;p=gitmo%2FMooseX-Singleton.git Do a bit of fixing. instance and new are one and the same. More tests to ensure that this is so. --- diff --git a/lib/MooseX/Singleton.pm b/lib/MooseX/Singleton.pm index 38f22ec..c0bb14d 100644 --- a/lib/MooseX/Singleton.pm +++ b/lib/MooseX/Singleton.pm @@ -1,27 +1,24 @@ package MooseX::Singleton; - use Moose::Role; -our $VERSION = 0.01; +our $VERSION = 0.02; override new => sub { - my ($class) = @_; - - no strict qw/refs/; + my ($class) = @_; - my $instance = super; + no strict 'refs'; - ${"$class\::singleton"} = $instance; + # create our instance if we don't already have one + if (!defined ${"$class\::singleton"}) { + ${"$class\::singleton"} = super; + } - return $instance; + return ${"$class\::singleton"}; }; +# instance really is the same as new. any ideas for a better implementation? sub instance { - my ($class) = @_; - - no strict qw/refs/; - - return ${"$class\::singleton"}; + shift->new(@_); } 1; diff --git a/t/singleton.t b/t/singleton.t index de4eab6..8f4ca17 100644 --- a/t/singleton.t +++ b/t/singleton.t @@ -1,25 +1,28 @@ -use Test::More tests => 2; +use Test::More tests => 4; use strict; use warnings; { - package Foo::Singleton; + package Foo::Singleton; + use Moose; - use Moose; + with qw/MooseX::Singleton/; - has gravy => (is => 'rw'); - - with qw/MooseX::Singleton/; + has gravy => (is => 'rw'); } -ok (Foo::Singleton->new,'new'); +my $ante = Foo::Singleton->instance; -my $foo = Foo::Singleton->instance; +ok(Foo::Singleton->new,'new'); +my $foo = Foo::Singleton->instance; my $bar = Foo::Singleton->instance; +my $baz = Foo::Singleton->new; -$foo->gravy ('sauce'); +$foo->gravy('sauce'); -is ($bar->gravy,'sauce','singleton'); +is($bar->gravy,'sauce','singleton'); +is($baz->gravy,'sauce','singleton'); +is($ante->gravy,'sauce','singleton');