summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authordoy <doy@tozt.net>2009-04-26 23:22:51 -0500
committerdoy <doy@tozt.net>2009-04-26 23:22:51 -0500
commite7148b49978b3e5888c070680d22dd3a7707e6d2 (patch)
tree5bc024815862878689826d93e443d2a1c6cfecfc
parent31f56db58c77fa4669fca406a3cd471e9b68f3dd (diff)
downloadbot-games-e7148b49978b3e5888c070680d22dd3a7707e6d2.tar.gz
bot-games-e7148b49978b3e5888c070680d22dd3a7707e6d2.zip
apply default formatters to attributes based on the attribute's type constraint, if none is set explicitly
-rw-r--r--lib/Bot/Games/Trait/Attribute/Formatted.pm29
1 files changed, 29 insertions, 0 deletions
diff --git a/lib/Bot/Games/Trait/Attribute/Formatted.pm b/lib/Bot/Games/Trait/Attribute/Formatted.pm
index 8eaa11c..ca4776f 100644
--- a/lib/Bot/Games/Trait/Attribute/Formatted.pm
+++ b/lib/Bot/Games/Trait/Attribute/Formatted.pm
@@ -1,6 +1,21 @@
package Bot::Games::Trait::Attribute::Formatted;
use Moose::Role;
+my %default_formatters = (
+ 'ArrayRef' => sub {
+ my $arrayref = shift;
+ return join ', ', @$arrayref;
+ },
+ 'Bool' => sub {
+ my $bool = shift;
+ return $bool ? 'true' : 'false';
+ },
+ 'Object' => sub {
+ my $obj = shift;
+ return "$obj";
+ },
+);
+
# when the attribute is being constructed, the accessor methods haven't been
# generated yet, so we need to store the formatter here, and then apply it
# after the accessor methods exist
@@ -17,6 +32,20 @@ before _process_options => sub {
if exists($options->{formatter}) && !$options->{command};
};
+after _process_options => sub {
+ my $self = shift;
+ my ($name, $options) = @_;
+ return if exists $options->{formatter};
+ if (exists $options->{type_constraint}) {
+ my $tc = $options->{type_constraint};
+ for my $tc_type (keys %default_formatters) {
+ if ($tc->is_a_type_of($tc_type)) {
+ $self->formatter($default_formatters{$tc_type});
+ }
+ }
+ }
+};
+
around accessor_metaclass => sub {
my $orig = shift;
my $self = shift;