You Can Have Your Moose and Eat it Too

It seems that my never ending story of AD&D Moose posts are coming to an end. I have a good bunch of code written and things are working quite well. I did run into a slight problem. If you remember this post where I was adding in the available classes seems I let a cheat get in there.

uPNKf.png

If a user declares a class before adding in a race this is is possible to get race-character combinations that are not allowed, such as Dwarf Magic-User or Halfling Paladin.

Now I could go back and add in some more if then else logic in my BUILD but this is an easy way to add the required test with only a slight modification of my BUILD.

On my Class and Race attribute I can add in the 'predicate' method to both like this


has 'race' =>(
is =>'rw',
isa =>'RPG::ADD::Creator::Race',
handles => {
allowed_classes => 'allowed_classes',
},
predicate => 'has_race',


);

has 'class' =>(
is =>'rw',
isa =>'RPG::ADD::Creator::Class',
predicate => 'has_class',
);

Now what Moose have given me with this is the ability to check to see if an attribute has been set. So in my begin code I can do this simple check first


throw_exception( "NeitherRoleNorRoleNameIsGiven", {message=>"You cannot have a Character with a Class and no Race"})
if ($self->has_class() and !$self->has_race() )

The only caveat with this little lump of sugar is if you know you are going to want to undef an attribute then you 'has_' will still see it as true not false. you will have to add in a 'cleaner' sub to tell Moose that the attribute is empty again.

I haven't found a use for 'cleaner' sugar yet but I am sure I will when I start playing around even more with the playing part of the game.

2 Comments

I believe you have a typo:

!$self->has_role()

should be

!$self->has_race()

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