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.In reply to Idea: Moose Mutual Coercion by k0st
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |