2 package MooseX::AttributeHelpers::Counter;
4 use Moose::Util::TypeConstraints;
7 our $AUTHORITY = 'cpan:STEVAN';
9 extends 'Moose::Meta::Attribute';
11 my %METHOD_CONSTRUCTORS = (
14 return sub { $attr->set_value($_[0], $attr->get_value($_[0]) + 1) };
18 return sub { $attr->set_value($_[0], $attr->get_value($_[0]) - 1) };
24 isa => subtype('HashRef' => where {
25 (exists $METHOD_CONSTRUCTORS{$_} || return) for keys %{$_}; 1;
30 has '+$!default' => (required => 1);
31 has '+type_constraint' => (required => 1);
33 before '_process_options' => sub {
34 my ($self, %options) = @_;
36 if (exists $options{provides}) {
37 (exists $options{isa})
38 || confess "You must define a type with the Counter metaclass";
40 (find_type_constraint($options{isa})->is_subtype_of('Num'))
41 || confess "The type constraint for a Counter must be a subtype of Num";
45 after 'install_accessors' => sub {
47 my $class = $attr->associated_class;
49 foreach my $key (keys %{$attr->provides}) {
50 (exists $METHOD_CONSTRUCTORS{$key})
51 || confess "Unsupported method type ($key)";
53 $attr->provides->{$key},
54 $METHOD_CONSTRUCTORS{$key}->($attr)
60 no Moose::Util::TypeConstraints;
62 # register the alias ...
63 package Moose::Meta::Attribute::Custom::Counter;
64 sub register_implementation { 'MooseX::AttributeHelpers::Counter' }
74 MooseX::AttributeHelpers::Counter
82 metaclass => 'Counter',
91 my $page = MyHomePage->new();
92 $page->inc_counter; # same as $page->counter($page->counter + 1);
100 All complex software has bugs lurking in it, and this module is no
101 exception. If you find a bug please either email me, or add the bug
106 Stevan Little E<lt>stevan@iinteractive.comE<gt>
108 =head1 COPYRIGHT AND LICENSE
110 Copyright 2007 by Infinity Interactive, Inc.
112 L<http://www.iinteractive.com>
114 This library is free software; you can redistribute it and/or modify
115 it under the same terms as Perl itself.