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