diff options
author | doy <doy@tozt.net> | 2009-04-26 22:24:14 -0500 |
---|---|---|
committer | doy <doy@tozt.net> | 2009-04-26 22:24:14 -0500 |
commit | 666ae159e66abf14e5ba3774f848f38be5940461 (patch) | |
tree | 23e97c925447559c0757e2a60dfb02b67d8482d3 /lib | |
parent | 32e96dd47b9ca6e2ee14f3c8ada101d45cd56c88 (diff) | |
download | bot-games-666ae159e66abf14e5ba3774f848f38be5940461.tar.gz bot-games-666ae159e66abf14e5ba3774f848f38be5940461.zip |
add roles for formatting the results of methods
Diffstat (limited to 'lib')
-rw-r--r-- | lib/Bot/Games/OO/Game.pm | 5 | ||||
-rw-r--r-- | lib/Bot/Games/Trait/Attribute/Formatted.pm | 25 | ||||
-rw-r--r-- | lib/Bot/Games/Trait/Method/Formatted.pm | 25 |
3 files changed, 54 insertions, 1 deletions
diff --git a/lib/Bot/Games/OO/Game.pm b/lib/Bot/Games/OO/Game.pm index 9f19fb7..e6cb762 100644 --- a/lib/Bot/Games/OO/Game.pm +++ b/lib/Bot/Games/OO/Game.pm @@ -40,7 +40,10 @@ sub init_meta { for_class => $options{for_class}, attribute_metaclass_roles => - ['Bot::Games::Trait::Attribute::Command'], + ['Bot::Games::Trait::Attribute::Command', + 'Bot::Games::Trait::Attribute::Formatted'], + method_metaclass_roles => + ['Bot::Games::Trait::Method::Formatted'], metaclass_roles => ['Bot::Games::Trait::Class::Command'], ); diff --git a/lib/Bot/Games/Trait/Attribute/Formatted.pm b/lib/Bot/Games/Trait/Attribute/Formatted.pm new file mode 100644 index 0000000..dd40a19 --- /dev/null +++ b/lib/Bot/Games/Trait/Attribute/Formatted.pm @@ -0,0 +1,25 @@ +package Bot::Games::Trait::Attribute::Formatted; +use Moose::Role; + +# 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 +has formatter => ( + is => 'rw', + isa => 'CodeRef', + predicate => 'has_formatter', +); + +after install_accessors => sub { + my $self = shift; + if ($self->has_formatter) { + my $formatter = $self->formatter; + my $method_meta = $self->get_read_method_ref; + $method_meta->formatter($formatter) + if $method_meta->can('formatter'); + } +}; + +no Moose::Role; + +1; diff --git a/lib/Bot/Games/Trait/Method/Formatted.pm b/lib/Bot/Games/Trait/Method/Formatted.pm new file mode 100644 index 0000000..f5e6415 --- /dev/null +++ b/lib/Bot/Games/Trait/Method/Formatted.pm @@ -0,0 +1,25 @@ +package Bot::Games::Trait::Method::Formatted; +use Moose::Role; + +has formatter => ( + is => 'rw', + isa => 'CodeRef', + default => sub { sub { + my $self = shift; + my ($to_print) = @_; + if (blessed $to_print) { + $to_print = "$to_print"; + } + elsif (ref($to_print) && ref($to_print) eq 'ARRAY') { + $to_print = join ', ', @$to_print; + } + elsif (!$to_print) { + $to_print = 'false'; + } + return $to_print; + } }, +); + +no Moose::Role; + +1; |