changelog
[gitmo/Moose.git] / lib / Moose / Cookbook / Extending / Recipe2.pod
CommitLineData
daa0fd7d 1package Moose::Cookbook::Extending::Recipe2;
2
3# ABSTRACT: Providing a role for the base object class
4
5__END__
6
f3ce0579 7
8=pod
9
6e646af9 10=begin testing-SETUP
11
0adca353 12use Test::Requires {
13 'Test::Output' => '0',
14};
6e646af9 15
16=end testing-SETUP
17
f3ce0579 18=head1 SYNOPSIS
19
20 package MooseX::Debugging;
21
f3ce0579 22 use Moose::Exporter;
f3ce0579 23
95056a1e 24 Moose::Exporter->setup_import_methods(
25 base_class_roles => ['MooseX::Debugging::Role::Object'],
26 );
f3ce0579 27
f3ce0579 28 package MooseX::Debugging::Role::Object;
29
0df6b748 30 use Moose::Role;
31
6e646af9 32 after 'BUILDALL' => sub {
f3ce0579 33 my $self = shift;
34
6e646af9 35 warn "Made a new " . ( ref $self ) . " object\n";
6a7e3999 36 };
f3ce0579 37
38=head1 DESCRIPTION
39
40In this example, we provide a role for the base object class that adds
41some simple debugging output. Every time an object is created, it
42spits out a warning saying what type of object it was.
43
44Obviously, a real debugging role would do something more interesting,
45but this recipe is all about how we apply that role.
46
47In this case, with the combination of L<Moose::Exporter> and
8efdbb91 48L<Moose::Util::MetaRole>, we ensure that when a module does C<S<use
49MooseX::Debugging>>, it automatically gets the debugging role applied
f3ce0579 50to its base object class.
51
871cda31 52There are a few pieces of code worth looking at more closely.
53
95056a1e 54 Moose::Exporter->setup_import_methods(
55 base_class_roles => ['MooseX::Debugging::Role::Object'],
56 );
871cda31 57
edd82429 58This creates an C<import> method in the C<MooseX::Debugging> package. Since we
59are not actually exporting anything, we do not pass C<setup_import_methods>
60any parameters related to exports, but we need to have an C<import> method to
61ensure that our C<init_meta> method is called. The C<init_meta> is created by
62C<setup_import_methods> for us, since we passed the C<base_class_roles>
63parameter. The generated C<init_meta> will in turn call
64L<Moose::Util::MetaRole::apply_base_class_roles|Moose::Util::MetaRole/apply_base_class_roles>.
871cda31 65
6e646af9 66=begin testing
67
68{
69 package Debugged;
f3ce0579 70
6e646af9 71 use Moose;
72 MooseX::Debugging->import;
73}
74
75stderr_is(
76 sub { Debugged->new },
77 "Made a new Debugged object\n",
78 'got expected output from debugging role'
79);
80
81=end testing
82
83=cut