Subject: | documentation: call turn_new_into_singleton in BUILD() |
Hi,
I'm using Role::Singleton::New, and I've run into a situation where I don't control when new is called, so cannot immediately call turn_new_into_singleton.
The solution was to put it in BUILD:
sub BUILD { $_[0]->turn_new_into_singleton }
I think that might be a useful addition to the documentation.
Unfortunately it's not something that you can put in the role to automatically happen (via modifying BUILD), as you can't modify a method which doesn't exist in the composing class (Class::Method::Modifiers seems really upset by this). If you turned the role into a class though, then you *could* get it done automatically, as the parent's BUILD will get called automatically.
----------------------------------------------------
package MySingleton;
use Moo;
with 'Role::Singleton::New';
sub BUILD { $_[0]->turn_new_into_singleton }
package Foo;
use Moo;
extends 'MySingleton';
has foo => ( is => 'rw' );
package main;
use 5.10.1;
say "1: ", Foo->new(foo => 3 )->foo;
say "2: ", Foo->new(foo => 5 )->foo;
----------------------------------------------------
which gets you:
% perl singleton.pl
1: 3
2: 3