Some prose cleanups
[gitmo/Moose.git] / t / 000_recipes / 022_attribute_trait.t
CommitLineData
e2a5f2c6 1#!/usr/bin/perl
2
3use strict;
4use warnings;
5
6use Test::More tests => 2;
7use Test::Exception;
8
9BEGIN {
10 use_ok('Moose');
11}
12
13## attribute trait example
14{
15
16 package MyApp::Meta::Attribute::Trait::Labeled;
17 use Moose::Role;
18
19 has label => (
20 is => 'rw',
21 isa => 'Str',
22 predicate => 'has_label',
23 );
24
25 package Moose::Meta::Attribute::Custom::Trait::Labeled;
26 sub register_implementation { 'MyApp::Meta::Attribute::Trait::Labeled' }
27
28 package MyApp::Website;
29 use Moose;
30
31 has url => (
32 traits => [qw/Labeled/],
33 isa => 'Str',
34 is => 'rw',
35 label => "The site's URL",
36 );
37
38 has name => (
39 is => 'rw',
40 isa => 'Str',
41 );
42
43 sub dump {
44 my $self = shift;
45
46 my $dump_value = '';
47
48 # iterate over all the attributes in $self
49 my %attributes = %{ $self->meta->get_attribute_map };
50 foreach my $name (sort keys %attributes) {
51
52 my $attribute = $attributes{$name};
53
54 # print the label if available
55 if ($attribute->does('MyApp::Meta::Attribute::Trait::Labeled')
56 && $attribute->has_label) {
57 $dump_value .= $attribute->label;
58 }
59 # otherwise print the name
60 else {
61 $dump_value .= $name;
62 }
63
64 # print the attribute's value
65 my $reader = $attribute->get_read_method;
66 $dump_value .= ": " . $self->$reader . "\n";
67 }
68
69 return $dump_value;
70 }
71
72}
73
74my $app = MyApp::Website->new(url => "http://google.com", name => "Google");
75is($app->dump, q{name: Google
76The site's URL: http://google.com
77}, '... got the expected dump value');
78
79
80