Axk/Object/TinyDefaults.pm untested

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