* changes for MooseX::IOC
[gitmo/MooseX-AttributeHelpers.git] / lib / MooseX / AttributeHelpers / Counter.pm
1
2 package MooseX::AttributeHelpers::Counter;
3 use Moose;
4 use Moose::Util::TypeConstraints;
5
6 our $VERSION   = '0.01';
7 our $AUTHORITY = 'cpan:STEVAN';
8
9 extends 'MooseX::AttributeHelpers::Base';
10
11 has '+method_constructors' => (
12     default => sub {
13         return +{
14             inc => sub {
15                 my $attr = shift;
16                 return sub { $attr->set_value($_[0], $attr->get_value($_[0]) + 1) };
17             },
18             dec => sub {
19                 my $attr = shift;
20                 return sub { $attr->set_value($_[0], $attr->get_value($_[0]) - 1) };        
21             },
22         }
23     }
24 );
25
26 sub _process_options_for_provides {
27     my ($self, $options) = @_;
28     (exists $options->{isa})
29         || confess "You must define a type with the Counter metaclass";  
30      
31     my $isa = $options->{isa}; 
32     
33     unless (blessed($isa) && $isa->isa('Moose::Meta::TypeConstraint')) {
34         $isa = find_type_constraint($isa);        
35     }
36     
37     ($isa->is_a_type_of('Num'))
38         || confess "The type constraint for a Counter ($options->{isa}) must be a subtype of Num";
39 }
40     
41 no Moose;
42 no Moose::Util::TypeConstraints;
43
44 # register the alias ...
45 package Moose::Meta::Attribute::Custom::Counter;
46 sub register_implementation { 'MooseX::AttributeHelpers::Counter' }
47
48 1;
49
50 __END__
51
52 =pod
53
54 =head1 NAME
55
56 MooseX::AttributeHelpers::Counter
57
58 =head1 SYNOPSIS
59
60   package MyHomePage;
61   use Moose;
62   
63   has 'counter' => (
64       metaclass => 'Counter',
65       is        => 'rw',
66       isa       => 'Int',
67       default   => sub { 0 },
68       provides  => {
69           inc => 'inc_counter',
70       }
71   );
72
73   my $page = MyHomePage->new();
74   $page->inc_counter; # same as $page->counter($page->counter + 1);
75   
76 =head1 DESCRIPTION
77
78 =head1 METHODS
79
80 =head1 BUGS
81
82 All complex software has bugs lurking in it, and this module is no 
83 exception. If you find a bug please either email me, or add the bug
84 to cpan-RT.
85
86 =head1 AUTHOR
87
88 Stevan Little E<lt>stevan@iinteractive.comE<gt>
89
90 =head1 COPYRIGHT AND LICENSE
91
92 Copyright 2007 by Infinity Interactive, Inc.
93
94 L<http://www.iinteractive.com>
95
96 This library is free software; you can redistribute it and/or modify
97 it under the same terms as Perl itself.
98
99 =cut