Moose Fine Print

Well scooping about looking at way to refactor some of my AD&D 'Creator' class code I stumbled on a nice little feature of Moose.

cook-nicerack-s.gif

Though not really standing out in the Moose documentation and not really hidden either is the fact that all of the declarative keywords are really just function calls.

So you might recall that I had this in my 'Creator' Class


with
'MooseX::Role::BuildInstanceOf' => {
target => 'RPG::ADD::Creator::Wisdom',
prefix => 'Wisdom',
constructor => 'new',
inherited_args => [{roll=>'wisdom'}],
},
...

repeated for each of the six abilities. It seems all I really had to do to cut down on all this repetition is this;

use Moose;
foreach my $ability (qw(Strength Intelligence Wisdom Charisma Constitution Dexterity)){
with 'MooseX::Role::BuildInstanceOf' => {
target => 'RPG::ADD::Creator::'.$ability,
prefix => $ability,
constructor => 'new',
inherited_args => [{roll=>lc($ability)}],

}
}

An it just works.

I can even mix and match the differing declaratives to get rid of even more repetition so now I just have



use Moose;
foreach my $ability (qw(Strength Intelligence Wisdom Charisma Constitution Dexterity)){
with 'MooseX::Role::BuildInstanceOf' => {
target => 'RPG::ADD::Creator::'.$ability,
prefix => $ability,
constructor => 'new',
inherited_args => [{roll=>lc($ability)}],

};

has lc($ability) =>(
is =>'rw',);
}

I snooped about quite a bit for this series and do not think I have seen this used in any other demos or in the docs except 'Attributes'. Though after thinking a bit it makes prefect sense once your realize the fact that the 'declaratives' are really just function calls.


I guess if the documenters where real old fart perl programmers, like me, they might of put brackets around the 'with' and the other declaritives and it it might of stood out more clearly, at least to me.

Oh well life is a learning experience.


Leave a comment

About byterock

user-pic Long time Perl guy, a few CPAN mods allot of work on DBD::Oracle and a few YAPC presentations