Object/TinyDefaults.pm untested

filter: Statementstmt 0.0% 0 / 54 Branchbran 0.0% 0 / 12 Conditioncond 0.0% 0 / 5 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 11 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 85 CC 7 SCAR 24.8
CC
7
Cov
0%
BEGIN
30.0
import
12.0
new
2.0
CRAP 12.0
1 #!/usr/bin/env perl
2 # Object::TinyDefaults - Object::Tiny::XS, but with default values.
3 # Copyright (c) 2018 cxw42. All rights reserved. Artistic 2.
4  
5 package Object::TinyDefaults;
6  
7 use 5.004;
8 use strict 'vars', 'subs';
9 use warnings;
10 use Data::Dumper;
11 use Import::Into;
12  
13 our $ObjTiny;
14 our $VERSION;
15 $VERSION = '0.01';
16  
17 BEGIN {
18 require parent;
19  
20 # Use Object::Tiny::XS or Object::Tiny
21 eval { require Object::Tiny::XS; };
22 $ObjTiny = 'Object::Tiny::XS' unless $@;
23 eval { require Object::Tiny; } unless $ObjTiny;
24 $ObjTiny = 'Object::Tiny' unless $@ || $ObjTiny;
25  
26 die 'Cannot find Object::Tiny or Object::Tiny::XS' unless $ObjTiny;
27 #print "Using $ObjTiny\n";
28 } # BEGIN
29  
30 my %defaults;
31  
32 # Import: If the first parameter is a hashref, it contains the defaults.
33 # Any remaining parameters are other fields to create. Field names in the
34 # defaults do not also have to be specified in the list.
35 sub import {
36 my $class = shift;
37 return unless $class eq __PACKAGE__;
38 # Without this, it also gets imported into XML::Axk::L1 and
39 # axk_script_*, trashing symbols and preventing execution.
40 my $pkg = caller;
41 #print "Import into $pkg: (", join(', ', @_), ")\n";
42  
43 # Stash defaults for new()
44 $defaults{$pkg} = { (ref $_[0] eq 'HASH') ? %{+shift} : () };
45 # Keep our own shallow copy of the defaults
46 #print "Defaults for $pkg are ", Dumper($defaults{$pkg}), "\n";
47  
48 parent->import::into(1, $class); # Caller is now a child of us
49 #print "Caller is now ", join(', ', @{$pkg . '::ISA'}), "\n";
50  
51 my %vars = %{$defaults{$pkg}}; # All the fields, without duplicates
52 $vars{$_} = 1 for @_;
53  
54 #print 'Fields are (', join(', ', keys %vars), ")\n";
55 $ObjTiny->import::into(1, keys %vars);
56 # Caller now has all the accessors, and is still a child of us because
57 # Object::Tiny doesn't overwrite an existing @ISA.
58  
59 #print "Done importing into $pkg\n";
60 return 1;
61 } #import()
62  
63 # new: Create a new instance. Constructor parameters are key=>value
64 # assignments that override the defaults.
65 sub new {
66 #print 'New: (', join(', ', @_), ")\n";
67 my $class = shift;
68  
69 my $hrOpts = $defaults{$class} // {}; # Grab defaults
70 my %self = %{$hrOpts};
71  
72 my $hrArgs = { @_ }; # Params override defaults
73 @self{keys %$hrArgs} = values %$hrArgs;
74  
75 return bless(\%self, $class);
76 } #new()
77  
78 1;
79  
80 __END__