File Coverage

blib/lib/Class/Data/Lite.pm
Criterion Covered Total %
statement 35 35 100.0
branch 9 10 90.0
condition n/a
subroutine 10 10 100.0
pod n/a
total 54 55 98.1


line stmt bran cond sub pod time code
1             package Class::Data::Lite;
2 4     4   170778 use 5.008001;
  4         31  
3 4     4   19 use strict;
  4         5  
  4         67  
4 4     4   14 use warnings;
  4         7  
  4         442  
5              
6             our $VERSION = "0.0010";
7              
8 1     1   7 sub _croak {require Carp; Carp::croak(@_) }
  1         213  
9              
10             sub import {
11 4     4   35 shift;
12 4         10 my %args = @_;
13 4         11 my $pkg = caller(0);
14              
15 4         11 my %key_ctor = (
16             rw => \&_mk_accessor,
17             ro => \&_mk_ro_accessor,
18             );
19              
20 4     4   33 no strict 'refs';
  4         6  
  4         1187  
21 4         12 for my $key (keys %key_ctor) {
22 8 100       34 if (my $accessors = delete $args{$key}) {
23 5 50       31 _croak "value of the '$key' parameter should be an arrayref or hashref"
24             unless ref($accessors) =~ /^(?:HASH|ARRAY)$/;
25 5 100       19 my %h = ref($accessors) eq 'HASH' ? %$accessors : map {($_ => undef)} @$accessors;
  2         5  
26 5         19 while (my ($k, $v) = each %h) {
27 7         16 *{"${pkg}::${k}"} = $key_ctor{$key}->($pkg, $k, $v);
  7         3334  
28             }
29             }
30             }
31             }
32              
33             sub _mk_accessor {
34 5     5   9 my ($pkg, $meth, $data) = @_;
35             return sub {
36 10 100   10   1095 if (@_>1) {
37 3 100       12 if ($_[0] ne $pkg) {
38             # In the case of rw, raise an exception here because there is a
39             # possibility of being overwritten from a child class.
40             # In the case of ro, there is no risk, so we do not raise
41             # exceptions in particular.
42 1         6 _croak qq[can't call "${pkg}::${meth}" as object method or inherited class method];
43             }
44 2         23 $data = $_[1];
45             }
46 9         33 $data;
47 5         16 };
48             }
49              
50             sub _mk_ro_accessor {
51 2     2   4 my ($pkg, $meth, $data) = @_;
52 2     3   7 return sub { $data };
  3         18  
53             }
54              
55             1;
56             __END__