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