Update to modernize recommendations and make example code use modern APIs
[gitmo/Moose.git] / lib / Moose / Cookbook / Meta / Recipe2.pod
1 package Moose::Cookbook::Meta::Recipe2;
2
3 # ABSTRACT: A meta-attribute, attributes with labels
4
5 __END__
6
7
8 =pod
9
10 =head1 SYNOPSIS
11
12   package MyApp::Meta::Attribute::Labeled;
13   use Moose;
14   extends 'Moose::Meta::Attribute';
15
16   has label => (
17       is        => 'rw',
18       isa       => 'Str',
19       predicate => 'has_label',
20   );
21
22   package Moose::Meta::Attribute::Custom::Labeled;
23   sub register_implementation {'MyApp::Meta::Attribute::Labeled'}
24
25   package MyApp::Website;
26   use Moose;
27
28   has url => (
29       metaclass => 'Labeled',
30       is        => 'rw',
31       isa       => 'Str',
32       label     => "The site's URL",
33   );
34
35   has name => (
36       is  => 'rw',
37       isa => 'Str',
38   );
39
40   sub dump {
41       my $self = shift;
42
43       my $meta = $self->meta;
44
45       my $dump = '';
46
47       for my $attribute ( map { $meta->get_attribute($_) }
48           sort $meta->get_attribute_list ) {
49
50           if (   $attribute->isa('MyApp::Meta::Attribute::Labeled')
51               && $attribute->has_label ) {
52               $dump .= $attribute->label;
53           }
54           else {
55               $dump .= $attribute->name;
56           }
57
58           my $reader = $attribute->get_read_method;
59           $dump .= ": " . $self->$reader . "\n";
60       }
61
62       return $dump;
63   }
64
65   package main;
66
67   my $app = MyApp::Website->new( url => "http://google.com", name => "Google" );
68
69 =head1 SUMMARY
70
71 In this recipe, we begin to delve into the wonder of meta-programming.
72 Some readers may scoff and claim that this is the arena of only the
73 most twisted Moose developers. Absolutely not! Any sufficiently
74 twisted developer can benefit greatly from going more meta.
75
76 Our goal is to allow each attribute to have a human-readable "label"
77 attached to it. Such labels would be used when showing data to an end
78 user. In this recipe we label the C<url> attribute with "The site's
79 URL" and create a simple method showing how to use that label.
80
81 The proper, modern way to extend attributes (using a role instead of a
82 subclass) is described in L<Moose::Cookbook::Meta::Recipe3>, but that recipe
83 assumes you've read and at least tried to understand this one.
84
85 =head1 META-ATTRIBUTE OBJECTS
86
87 All the attributes of a Moose-based object are actually objects
88 themselves.  These objects have methods and attributes. Let's look at
89 a concrete example.
90
91   has 'x' => ( isa => 'Int', is => 'ro' );
92   has 'y' => ( isa => 'Int', is => 'rw' );
93
94 Internally, the metaclass for C<Point> has two
95 L<Moose::Meta::Attribute>. There are several methods for getting
96 meta-attributes out of a metaclass, one of which is
97 C<get_attribute_list>. This method is called on the metaclass object.
98
99 The C<get_attribute_list> method returns a list of attribute names. You can
100 then use C<get_attribute> to get the L<Moose::Meta::Attribute> object itself.
101
102 Once you have this meta-attribute object, you can call methods on it like this:
103
104   print $point->meta->get_attribute('x')->type_constraint;
105      => Int
106
107 To add a label to our attributes there are two steps. First, we need a
108 new attribute metaclass that can store a label for an
109 attribute. Second, we need to create attributes that use that
110 attribute metaclass.
111
112 =head1 RECIPE REVIEW
113
114 We start by creating a new attribute metaclass.
115
116   package MyApp::Meta::Attribute::Labeled;
117   use Moose;
118   extends 'Moose::Meta::Attribute';
119
120 We can subclass a Moose metaclass in the same way that we subclass
121 anything else.
122
123   has label => (
124       is        => 'rw',
125       isa       => 'Str',
126       predicate => 'has_label',
127   );
128
129 Again, this is standard Moose code.
130
131 Then we need to register our metaclass with Moose:
132
133   package Moose::Meta::Attribute::Custom::Labeled;
134   sub register_implementation { 'MyApp::Meta::Attribute::Labeled' }
135
136 This is a bit of magic that lets us use a short name, "Labeled", when
137 referring to our new metaclass.
138
139 That was the whole attribute metaclass.
140
141 Now we start using it.
142
143   package MyApp::Website;
144   use Moose;
145   use MyApp::Meta::Attribute::Labeled;
146
147 We have to load the metaclass to use it, just like any Perl class.
148
149 Finally, we use it for an attribute:
150
151   has url => (
152       metaclass => 'Labeled',
153       is        => 'rw',
154       isa       => 'Str',
155       label     => "The site's URL",
156   );
157
158 This looks like a normal attribute declaration, except for two things,
159 the C<metaclass> and C<label> parameters. The C<metaclass> parameter
160 tells Moose we want to use a custom metaclass for this (one)
161 attribute. The C<label> parameter will be stored in the meta-attribute
162 object.
163
164 The reason that we can pass the name C<Labeled>, instead of
165 C<MyApp::Meta::Attribute::Labeled>, is because of the
166 C<register_implementation> code we touched on previously.
167
168 When you pass a metaclass to C<has>, it will take the name you provide
169 and prefix it with C<Moose::Meta::Attribute::Custom::>. Then it calls
170 C<register_implementation> in the package. In this case, that means
171 Moose ends up calling
172 C<Moose::Meta::Attribute::Custom::Labeled::register_implementation>.
173
174 If this function exists, it should return the I<real> metaclass
175 package name. This is exactly what our code does, returning
176 C<MyApp::Meta::Attribute::Labeled>. This is a little convoluted, and
177 if you don't like it, you can always use the fully-qualified name.
178
179 We can access this meta-attribute and its label like this:
180
181   $website->meta->get_attribute('url')->label()
182
183   MyApp::Website->meta->get_attribute('url')->label()
184
185 We also have a regular attribute, C<name>:
186
187   has name => (
188       is  => 'rw',
189       isa => 'Str',
190   );
191
192 This is a regular Moose attribute, because we have not specified a new
193 metaclass.
194
195 Finally, we have a C<dump> method, which creates a human-readable
196 representation of a C<MyApp::Website> object. It will use an
197 attribute's label if it has one.
198
199   sub dump {
200       my $self = shift;
201
202       my $meta = $self->meta;
203
204       my $dump = '';
205
206       for my $attribute ( map { $meta->get_attribute($_) }
207           sort $meta->get_attribute_list ) {
208
209           if (   $attribute->isa('MyApp::Meta::Attribute::Labeled')
210               && $attribute->has_label ) {
211               $dump .= $attribute->label;
212           }
213
214 This is a bit of defensive code. We cannot depend on every
215 meta-attribute having a label. Even if we define one for every
216 attribute in our class, a subclass may neglect to do so. Or a
217 superclass could add an attribute without a label.
218
219 We also check that the attribute has a label using the predicate we
220 defined. We could instead make the label C<required>. If we have a
221 label, we use it, otherwise we use the attribute name:
222
223           else {
224               $dump .= $attribute->name;
225           }
226
227           my $reader = $attribute->get_read_method;
228           $dump .= ": " . $self->$reader . "\n";
229       }
230
231       return $dump;
232   }
233
234 The C<get_read_method> is part of the L<Moose::Meta::Attribute>
235 API. It returns the name of a method that can read the attribute's
236 value, I<when called on the real object> (don't call this on the
237 meta-attribute).
238
239 =head1 CONCLUSION
240
241 You might wonder why you'd bother with all this. You could just
242 hardcode "The Site's URL" in the C<dump> method. But we want to avoid
243 repetition. If you need the label once, you may need it elsewhere,
244 maybe in the C<as_form> method you write next.
245
246 Associating a label with an attribute just makes sense! The label is a
247 piece of information I<about> the attribute.
248
249 It's also important to realize that this was a trivial example. You
250 can make much more powerful metaclasses that I<do> things, as opposed
251 to just storing some more information. For example, you could
252 implement a metaclass that expires attributes after a certain amount
253 of time:
254
255    has site_cache => (
256        metaclass     => 'TimedExpiry',
257        expires_after => { hours => 1 },
258        refresh_with  => sub { get( $_[0]->url ) },
259        isa           => 'Str',
260        is            => 'ro',
261    );
262
263 The sky's the limit!
264
265 =begin testing
266
267 my $app = MyApp::Website->new( url => "http://google.com", name => "Google" );
268 is(
269     $app->dump, q{name: Google
270 The site's URL: http://google.com
271 }, '... got the expected dump value'
272 );
273
274 =end testing
275
276 =cut
277