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