package Identity; use Moose; subtype 'first_name_type', as 'Str'; where {/^\S+$}; subtype 'last_name_type', as 'Str'; where {/^\S+$}; subtype 'full_name_type', as 'Str', where {/^\S+ \S+$/}; coerce 'first_name_type', from 'full_name_type', via {(split(' '))[0]}; coerce 'last_name_type', from 'full_name_type', via {(split(' '))[1]}; has 'first_name' => ( isa => 'first_name_type', coerce => 1, lazy => 1, default => sub {$_[0]->full_name}, ); has 'last_name' => ( isa => 'last_name_type', coerce => 1, lazy => 1 default => sub {$_[0]->full_name}, ); has 'full_name' => ( isa => 'full_name_type', coerce => 1, lazy => 1, default => sub {$_[0]->first_name.' '.$_[0]->last +_name}, );
The idea is that if you've set last_name and first_name already and then you call full_name it will build full_name from first_name and last_name and vise versa. Doing it this way isn't too bad but if keep adding new ways of making things the default methods get a lot of if statements in them and get annoying.
What if we could just declare full_name with something like this:has 'full_name' => ( isa => 'full_name_type', build_by => { A => 'first_name', B => 'last_name', with => 'A B', },
and that would do all the coercions and default methods behind the scenes.
When calling full_name for the first time (assuming first and last have been initialized) it would build it by replacing A and B in the string with the corresponding attributes first_name and last_name.
When calling last_name or first_name for the first time (assuming full_name had already been set) it would build them by looking at where they are in the string, and applying an appropriate regex (or whatever) to full_name to produce them. You wouldn't have to put a build_by in first/last name it would just recognize that full_name can use both of them to create itself and therefore it can be used to create them by reversing whatever you do to create it.
Well that's my idea. It could get much cooler and more advanced than that. If people respond/are interested I'll talk about it some more. I've never extended moose so I'm also interested in what people have to say about where to start to do something like this.Thanks for reading
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Idea: Moose Mutal Coercion
by tye (Sage) on Feb 14, 2012 at 14:22 UTC | |
by tobyink (Canon) on Feb 14, 2012 at 14:43 UTC | |
by Old_Gray_Bear (Bishop) on Feb 14, 2012 at 17:18 UTC | |
by k0st (Novice) on Feb 15, 2012 at 10:46 UTC | |
by tobyink (Canon) on Feb 16, 2012 at 08:36 UTC | |
by BrowserUk (Patriarch) on Feb 15, 2012 at 11:03 UTC | |
by educated_foo (Vicar) on Feb 15, 2012 at 13:58 UTC | |
by BrowserUk (Patriarch) on Feb 15, 2012 at 14:31 UTC | |
| |
Re: Idea: Moose Mutal Coercion
by educated_foo (Vicar) on Feb 14, 2012 at 12:13 UTC | |
by duelafn (Parson) on Feb 14, 2012 at 15:04 UTC | |
Re: Idea: Moose Mutual Coercion
by sundialsvc4 (Abbot) on Feb 15, 2012 at 15:32 UTC |