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