File: 021_meta_attribute.t

package info (click to toggle)
libmoose-perl 0.54-1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 1,496 kB
  • ctags: 448
  • sloc: perl: 15,125; makefile: 10
file content (80 lines) | stat: -rw-r--r-- 1,773 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/usr/bin/perl

use strict;
use warnings;

use Test::More tests => 2;
use Test::Exception;

BEGIN {
    use_ok('Moose');           
}

## meta-attribute example
{

    package MyApp::Meta::Attribute::Labeled;
    use Moose;
    extends 'Moose::Meta::Attribute';

    has label => (
        is  => 'rw',
        isa => 'Str',
        predicate => 'has_label',
    );

    package Moose::Meta::Attribute::Custom::Labeled;
    sub register_implementation { 'MyApp::Meta::Attribute::Labeled' }

    package MyApp::Website;
    use Moose;

    has url => (
        metaclass => 'Labeled',
        isa => 'Str',
        is => 'rw',
        label => "The site's URL",
    );

    has name => (
        is => 'rw',
        isa => 'Str',
    );

    sub dump {
        my $self = shift;

        my $dump_value = '';
        
        # iterate over all the attributes in $self
        my %attributes = %{ $self->meta->get_attribute_map };
        foreach my $name (sort keys %attributes) {
    
            my $attribute = $attributes{$name};
            
            # print the label if available
            if ($attribute->isa('MyApp::Meta::Attribute::Labeled')
                && $attribute->has_label) {
                    $dump_value .= $attribute->label;
            }
            # otherwise print the name
            else {
                $dump_value .= $name;
            }

            # print the attribute's value
            my $reader = $attribute->get_read_method;
            $dump_value .= ": " . $self->$reader . "\n";
        }
        
        return $dump_value;
    }

}

my $app = MyApp::Website->new(url => "http://google.com", name => "Google");
is($app->dump, q{name: Google
The site's URL: http://google.com
}, '... got the expected dump value');