Commit | Line | Data |
a5e51f0b |
1 | #!/usr/bin/perl |
2 | |
3 | use strict; |
4 | use warnings; |
5 | |
efd3d14c |
6 | use Test::More tests => 15; |
a5e51f0b |
7 | use Test::Exception; |
8 | |
efd3d14c |
9 | BEGIN {use Class::MOP; |
a5e51f0b |
10 | } |
11 | |
12 | { |
13 | package My::Meta::Package; |
14 | |
15 | use strict; |
16 | use warnings; |
17 | |
18 | use Carp 'confess'; |
19 | use Symbol 'gensym'; |
20 | |
21 | use base 'Class::MOP::Package'; |
22 | |
23 | __PACKAGE__->meta->add_attribute( |
1aeb4c53 |
24 | 'namespace' => ( |
56dcfc1a |
25 | reader => 'namespace', |
a5e51f0b |
26 | default => sub { {} } |
27 | ) |
28 | ); |
29 | |
30 | sub add_package_symbol { |
31 | my ($self, $variable, $initial_value) = @_; |
32 | |
33 | my ($name, $sigil, $type) = $self->_deconstruct_variable_name($variable); |
34 | |
35 | my $glob = gensym(); |
36 | *{$glob} = $initial_value if defined $initial_value; |
37 | $self->namespace->{$name} = $glob; |
38 | } |
39 | } |
40 | |
41 | # No actually package Foo exists :) |
a5e51f0b |
42 | my $meta = My::Meta::Package->initialize('Foo'); |
43 | |
44 | isa_ok($meta, 'My::Meta::Package'); |
45 | isa_ok($meta, 'Class::MOP::Package'); |
46 | |
47 | ok(!defined($Foo::{foo}), '... the %foo slot has not been created yet'); |
48 | ok(!$meta->has_package_symbol('%foo'), '... the meta agrees'); |
49 | |
50 | lives_ok { |
51 | $meta->add_package_symbol('%foo' => { one => 1 }); |
52 | } '... the %foo symbol is created succcessfully'; |
53 | |
54 | ok(!defined($Foo::{foo}), '... the %foo slot has not been created in the actual Foo package'); |
55 | ok($meta->has_package_symbol('%foo'), '... the meta agrees'); |
56 | |
57 | my $foo = $meta->get_package_symbol('%foo'); |
58 | is_deeply({ one => 1 }, $foo, '... got the right package variable back'); |
59 | |
60 | $foo->{two} = 2; |
61 | |
62 | is($foo, $meta->get_package_symbol('%foo'), '... our %foo is the same as the metas'); |
63 | |
64 | ok(!defined($Foo::{bar}), '... the @bar slot has not been created yet'); |
65 | |
66 | lives_ok { |
67 | $meta->add_package_symbol('@bar' => [ 1, 2, 3 ]); |
68 | } '... created @Foo::bar successfully'; |
69 | |
70 | ok(!defined($Foo::{bar}), '... the @bar slot has still not been created'); |
71 | |
72 | ok(!defined($Foo::{baz}), '... the %baz slot has not been created yet'); |
73 | |
74 | lives_ok { |
75 | $meta->add_package_symbol('%baz'); |
76 | } '... created %Foo::baz successfully'; |
77 | |
78 | ok(!defined($Foo::{baz}), '... the %baz slot has still not been created'); |
79 | |