I have an guest object that stores information. It has several attributes, including an array of stay history records that are Moose::Meta::Attribute::Native::Trait::Array objects. I wanted a special handler method on it that always sorted the stay objects in "EndDate" order. I also needed to display all this info in a Template::Toolkit template.<br>
<br>My Moose config for the "StayHistory" object ended up like this in the parent class: <br><br>...<br>has 'StayHistory' => ( # Moose::Meta::Attribute::Native::Trait::Array<br> traits => ['Array'], # of Omni2::Control::OWS::HotelReservation objects<br>
is => 'ro',<br> isa => 'ArrayRef[Object]',<br> default => sub { [] },<br> handles => {<br> all_stays => 'elements',<br> add_stay => 'push',<br>
map_stays => 'map',<br> filter_stay => 'grep',<br> find_stay => 'first',<br> get_stay => 'get',<br> join_stays => 'join',<br> count_stays => 'count',<br>
has_stays => 'count',<br> has_no_stays => 'is_empty',<br> sorted_stays => [ sort => sub { $_[1]->EndDate cmp $_[0]->EndDate } ],<br> },<br>);<br>...<br><br>Here's my actual StayHistory Moose attributes, any of which can be sorted on using the above method:<br>
<br>package Omni2::Control::OWS::StayHistory;<br>use Moose;<br>has '_twig' => (is => 'rw', isa => 'Object', required => 1); # XML::Twig::Elt<br>has 'site' => (is => 'rw', isa => 'Str', default=>'OM');<br>
has 'UniqueID' => (is => 'rw', isa => 'Str');<br>has 'StartDate' => (is => 'rw', isa => 'Str');<br>has 'EndDate' => (is => 'rw', isa => 'Str');<br>
has 'hotelCode' => (is => 'rw', isa => 'Str');<br>has 'Base' => (is => 'rw', isa => 'Str');<br>has 'Total' => (is => 'rw', isa => 'Str');<br>
has 'currencyCode' => (is => 'rw', isa => 'Str');<br>has 'ADULT' => (is => 'rw', isa => 'Str');<br>has 'CHILD' => (is => 'rw', isa => 'Str');<br>
...<br><br>All I had to do was add a FOREACH in TT and use the "sorted_stays" method above:<br>...<br> [% FOREACH row IN sg.sorted_stays %]<br> <tr onMouseover="this.bgColor='#FFFFFF'"onMouseout="this.bgColor='#F7EDD3'"><br>
<td>OM</td><br> <td>[% row.UniqueID %]</td><br> <td>[% row.hotelCode %]</td><br> <td>[% row.StartDate %]</td><br> <td>[% row.EndDate %]</td><br>
<td>[% row.ADULT %]</td><br> <td>[% row.CHILD %]</td><br> <td>[% row.Base %]</td><br> <td>[% row.Total %]</td><br> <td>[% row.currencyCode %]</td><br>
</tr><br> [% END %]<br>...<br><br>Easy!<br><br>