Class-Base-0.09/0000775000175000017500000000000013223464640012703 5ustar yanickyanickClass-Base-0.09/xt/0000775000175000017500000000000013223464640013336 5ustar yanickyanickClass-Base-0.09/xt/release/0000775000175000017500000000000013223464640014756 5ustar yanickyanickClass-Base-0.09/xt/release/unused-vars.t0000644000175000017500000000036213223464640017416 0ustar yanickyanick#!perl use Test::More 0.96 tests => 1; eval { require Test::Vars }; SKIP: { skip 1 => 'Test::Vars required for testing for unused vars' if $@; Test::Vars->import; subtest 'unused vars' => sub { all_vars_ok(); }; }; Class-Base-0.09/lib/0000775000175000017500000000000013223464640013451 5ustar yanickyanickClass-Base-0.09/lib/Class/0000775000175000017500000000000013223464640014516 5ustar yanickyanickClass-Base-0.09/lib/Class/Base.pm0000644000175000017500000005554613223464640015743 0ustar yanickyanickpackage Class::Base; our $AUTHORITY = 'cpan:YANICK'; # ABSTRACT: useful base class for deriving other modules $Class::Base::VERSION = '0.09'; use strict; use warnings; use Clone; #------------------------------------------------------------------------ # new(@config) # new(\%config) # # General purpose constructor method which expects a hash reference of # configuration parameters, or a list of name => value pairs which are # folded into a hash. Blesses a hash into an object and calls its # init() method, passing the parameter hash reference. Returns a new # object derived from Class::Base, or undef on error. #------------------------------------------------------------------------ sub new { my $class = shift; # allow hash ref as first argument, otherwise fold args into hash my $config = defined $_[0] && UNIVERSAL::isa($_[0], 'HASH') ? shift : { @_ }; no strict 'refs'; my $debug = defined $config->{ debug } ? $config->{ debug } : defined $config->{ DEBUG } ? $config->{ DEBUG } : ( do { local $^W; ${"$class\::DEBUG"} } || 0 ); my $self = bless { _ID => $config->{ id } || $config->{ ID } || $class, _DEBUG => $debug, _ERROR => '', }, $class; return $self->init($config) || $class->error($self->error()); } #------------------------------------------------------------------------ # init() # # Initialisation method called by the new() constructor and passing a # reference to a hash array containing any configuration items specified # as constructor arguments. Should return $self on success or undef on # error, via a call to the error() method to set the error message. #------------------------------------------------------------------------ sub init { return $_[0]; } #------------------------------------------------------------------------ # clone() # # Method to perform a simple clone of the current object hash and return # a new object. #------------------------------------------------------------------------ sub clone { return Clone::clone(shift); } #------------------------------------------------------------------------ # error() # error($msg, ...) # # May be called as a class or object method to set or retrieve the # package variable $ERROR (class method) or internal member # $self->{ _ERROR } (object method). The presence of parameters indicates # that the error value should be set. Undef is then returned. In the # abscence of parameters, the current error value is returned. #------------------------------------------------------------------------ sub error { my $self = shift; my $errvar = do { # get a reference to the object or package variable we're munging no strict qw( refs ); ref $self ? \$self->{ _ERROR } : \${"$self\::ERROR"}; }; if (@_) { # don't join if first arg is an object (may force stringification) $$errvar = ref($_[0]) ? shift : join('', @_); return undef; } return $$errvar; } #------------------------------------------------------------------------ # id($new_id) # # Method to get/set the internal _ID field which is used to identify # the object for the purposes of debugging, etc. #------------------------------------------------------------------------ sub id { my $self = shift; # set _ID with $obj->id('foo') return ($self->{ _ID } = shift) if ref $self && @_; # otherwise return id as $self->{ _ID } or class name my $id; $id = $self->{ _ID } if ref $self; $id ||= ref($self) || $self; return $id; } #------------------------------------------------------------------------ # params($vals, @keys) # params($vals, \@keys) # params($vals, \%keys) # # Utility method to examine the $config hash for any keys specified in # @keys and copy the values into $self. Keys should be specified as a # list or reference to a list of UPPER CASE names. The method looks # for either the name in either UPPER or lower case in the $config # hash and copies the value, if defined, into $self. The keys can # also be specified as a reference to a hash containing default values # or references to handler subroutines which will be called, passing # ($self, $config, $UPPER_KEY_NAME) as arguments. #------------------------------------------------------------------------ sub params { my $self = shift; my $vals = shift; my ($keys, @names); my ($key, $lckey, $default, $value, @values); if (@_) { if (ref $_[0] eq 'ARRAY') { $keys = shift; @names = @$keys; $keys = { map { ($_, undef) } @names }; } elsif (ref $_[0] eq 'HASH') { $keys = shift; @names = keys %$keys; } else { @names = @_; $keys = { map { ($_, undef) } @names }; } } else { $keys = { }; } foreach $key (@names) { $lckey = lc $key; # look for value provided in $vals hash defined($value = $vals->{ $key }) || ($value = $vals->{ $lckey }); # look for default which may be a code handler if (defined ($default = $keys->{ $key }) && ref $default eq 'CODE') { eval { $value = &$default($self, $key, $value); }; return $self->error($@) if $@; } else { $value = $default unless defined $value; $self->{ $key } = $value if defined $value; } push(@values, $value); delete @$vals{ $key, lc $key }; } return wantarray ? @values : \@values; } #------------------------------------------------------------------------ # debug(@args) # # Debug method which prints all arguments passed to STDERR if and only if # the appropriate DEBUG flag(s) are set. If called as an object method # where the object has a _DEBUG member defined then the value of that # flag is used. Otherwise, the $DEBUG package variable in the caller's # class is used as the flag to enable/disable debugging. #------------------------------------------------------------------------ sub debug { my $self = shift; my ($flag); if (ref $self && defined $self->{ _DEBUG }) { $flag = $self->{ _DEBUG }; } else { # go looking for package variable no strict 'refs'; $self = ref $self || $self; $flag = ${"$self\::DEBUG"}; } return unless $flag; print STDERR '[', $self->id, '] ', @_; } #------------------------------------------------------------------------ # debugging($flag) # # Method to turn debugging on/off (when called with an argument) or to # retrieve the current debugging status (when called without). Changes # to the debugging status are propagated to the $DEBUG variable in the # caller's package. #------------------------------------------------------------------------ sub debugging { my $self = shift; no strict 'refs'; my $dbgvar = ref $self ? \$self->{ _DEBUG } : \${"$self\::DEBUG"}; return @_ ? ($$dbgvar = shift) : $$dbgvar; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Class::Base - useful base class for deriving other modules =head1 VERSION version 0.09 =head1 SYNOPSIS package My::Funky::Module; use base qw( Class::Base ); # custom initialiser method sub init { my ($self, $config) = @_; # copy various params into $self $self->params($config, qw( FOO BAR BAZ )) || return undef; # to indicate a failure return $self->error('bad constructor!') if $something_bad; # or to indicate general happiness and well-being return $self; } package main; # new() constructor folds args into hash and calls init() my $object = My::Funky::Module->new( foo => 'bar', ... ) || die My::Funky::Module->error(); # error() class/object method to get/set errors $object->error('something has gone wrong'); print $object->error(); # debugging() method (de-)activates the debug() method $object->debugging(1); # debug() prints to STDERR if debugging enabled $object->debug('The ', $animal, ' sat on the ', $place); =head1 DESCRIPTION Please consider using L instead which is the successor of this module. This module implements a simple base class from which other modules can be derived, thereby inheriting a number of useful methods such as C, C, C, C, C and C. For a number of years, I found myself re-writing this module for practically every Perl project of any significant size. Or rather, I would copy the module from the last project and perform a global search and replace to change the names. Each time it got a little more polished and eventually, I decided to Do The Right Thing and release it as a module in it's own right. It doesn't pretend to be an all-encompassing solution for every kind of object creation problem you might encounter. In fact, it only supports blessed hash references that are created using the popular, but by no means universal convention of calling C with a list or reference to a hash array of named parameters. Constructor failure is indicated by returning undef and setting the C<$ERROR> package variable in the module's class to contain a relevant message (which you can also fetch by calling C as a class method). e.g. my $object = My::Module->new( file => 'myfile.html', msg => 'Hello World' ) || die $My::Module::ERROR; or: my $object = My::Module->new({ file => 'myfile.html', msg => 'Hello World', }) || die My::Module->error(); The C method handles the conversion of a list of arguments into a hash array and calls the C method to perform any initialisation. In many cases, it is therefore sufficient to define a module like so: package My::Module; use Class::Base; use base qw( Class::Base ); sub init { my ($self, $config) = @_; # copy some config items into $self $self->params($config, qw( FOO BAR )) || return undef; return $self; } # ...plus other application-specific methods 1; Then you can go right ahead and use it like this: use My::Module; my $object = My::Module->new( FOO => 'the foo value', BAR => 'the bar value' ) || die $My::Module::ERROR; Despite its limitations, Class::Base can be a surprisingly useful module to have lying around for those times where you just want to create a regular object based on a blessed hash reference and don't want to worry too much about duplicating the same old code to bless a hash, define configuration values, provide an error reporting mechanism, and so on. Simply derive your module from C and leave it to worry about most of the detail. And don't forget, you can always redefine your own C, C, or other method, if you don't like the way the Class::Base version works. =head2 Subclassing Class::Base This module is what object-oriented afficionados would describe as an "abstract base class". That means that it's not designed to be used as a stand-alone module, rather as something from which you derive your own modules. Like this: package My::Funky::Module use base qw( Class::Base ); You can then use it like this: use My::Funky::Module; my $module = My::Funky::Module->new(); =head2 Construction and Initialisation Methods If you want to apply any per-object initialisation, then simply write an C method. This gets called by the C method which passes a reference to a hash reference of configuration options. sub init { my ($self, $config) = @_; ... return $self; } When you create new objects using the C method you can either pass a hash reference or list of named arguments. The C method does the right thing to fold named arguments into a hash reference for passing to the C method. Thus, the following are equivalent: # hash reference my $module = My::Funky::Module->new({ foo => 'bar', wiz => 'waz', }); # list of named arguments (no enclosing '{' ... '}') my $module = My::Funky::Module->new( foo => 'bar', wiz => 'waz' ); Within the C method, you can either handle the configuration yourself: sub init { my ($self, $config) = @_; $self->{ file } = $config->{ file } || return $self->error('no file specified'); return $self; } or you can call the C method to do it for you: sub init { my ($self, $config) = @_; $self->params($config, 'file') || return $self->error('no file specified'); return $self; } =head2 Error Handling The C method should return $self to indicate success or undef to indicate a failure. You can use the C method to report an error within the C method. The C method returns undef, so you can use it like this: sub init { my ($self, $config) = @_; # let's make 'foobar' a mandatory argument $self->{ foobar } = $config->{ foobar } || return $self->error("no foobar argument"); return $self; } When you create objects of this class via C, you should now check the return value. If undef is returned then the error message can be retrieved by calling C as a class method. my $module = My::Funky::Module->new() || die My::Funky::Module->error(); Alternately, you can inspect the C<$ERROR> package variable which will contain the same error message. my $module = My::Funky::Module->new() || die $My::Funky::Module::ERROR; Of course, being a conscientious Perl programmer, you will want to be sure that the C<$ERROR> package variable is correctly defined. package My::Funky::Module use base qw( Class::Base ); our $ERROR; You can also call C as an object method. If you pass an argument then it will be used to set the internal error message for the object and return undef. Typically this is used within the module methods to report errors. sub another_method { my $self = shift; ... # set the object error return $self->error('something bad happened'); } If you don't pass an argument then the C method returns the current error value. Typically this is called from outside the object to determine its status. For example: my $object = My::Funky::Module->new() || die My::Funky::Module->error(); $object->another_method() || die $object->error(); =head2 Debugging Methods The module implements two methods to assist in writing debugging code: debug() and debugging(). Debugging can be enabled on a per-object or per-class basis, or as a combination of the two. When creating an object, you can set the C flag (or lower case C if you prefer) to enable or disable debugging for that one object. my $object = My::Funky::Module->new( debug => 1 ) || die My::Funky::Module->error(); my $object = My::Funky::Module->new( DEBUG => 1 ) || die My::Funky::Module->error(); If you don't explicitly specify a debugging flag then it assumes the value of the C<$DEBUG> package variable in your derived class or 0 if that isn't defined. You can also switch debugging on or off via the C method. $object->debugging(0); # debug off $object->debugging(1); # debug on The C method examines the internal debugging flag (the C<_DEBUG> member within the C<$self> hash) and if it finds it set to any true value then it prints to STDERR all the arguments passed to it. The output is prefixed by a tag containing the class name of the object in square brackets (but see the C method below for details on how to change that value). For example, calling the method as: $object->debug('foo', 'bar'); prints the following output to STDERR: [My::Funky::Module] foobar When called as class methods, C and C instead use the C<$DEBUG> package variable in the derived class as a flag to control debugging. This variable also defines the default C flag for any objects subsequently created via the new() method. package My::Funky::Module use base qw( Class::Base ); our $ERROR; our $DEBUG = 0 unless defined $DEBUG; # some time later, in a module far, far away package main; # debugging off (by default) my $object1 = My::Funky::Module->new(); # turn debugging on for My::Funky::Module objects $My::Funky::Module::DEBUG = 1; # alternate syntax My::Funky::Module->debugging(1); # debugging on (implicitly from $DEBUG package var) my $object2 = My::Funky::Module->new(); # debugging off (explicit override) my $object3 = My::Funky::Module->new(debug => 0); If you call C without any arguments then it returns the value of the internal object flag or the package variable accordingly. print "debugging is turned ", $object->debugging() ? 'on' : 'off'; =head1 METHODS =head2 new() Class constructor method which expects a reference to a hash array of parameters or a list of C value> pairs which are automagically folded into a hash reference. The method blesses a hash reference and then calls the C method, passing the reference to the hash array of configuration parameters. Returns a reference to an object on success or undef on error. In the latter case, the C method can be called as a class method, or the C<$ERROR> package variable (in the derived class' package) can be inspected to return an appropriate error message. my $object = My::Class->new( foo => 'bar' ) # params list || die $My::Class::$ERROR; # package var or my $object = My::Class->new({ foo => 'bar' }) # params hashref || die My::Class->error; # class method =head2 init(\%config) Object initialiser method which is called by the C method, passing a reference to a hash array of configuration parameters. The method may be derived in a subclass to perform any initialisation required. It should return C<$self> on success, or C on error, via a call to the C method. package My::Module; use base qw( Class::Base ); sub init { my ($self, $config) = @_; # let's make 'foobar' a mandatory argument $self->{ foobar } = $config->{ foobar } || return $self->error("no foobar argument"); return $self; } =head2 params($config, @keys) The C method accept a reference to a hash array as the first argument containing configuration values such as those passed to the C method. The second argument can be a reference to a list of parameter names or a reference to a hash array mapping parameter names to default values. If the second argument is not a reference then all the remaining arguments are taken as parameter names. Thus the method can be called as follows: sub init { my ($self, $config) = @_; # either... $self->params($config, qw( foo bar )); # or... $self->params($config, [ qw( foo bar ) ]); # or... $self->params($config, { foo => 'default foo value', bar => 'default bar value' } ); return $self; } The method looks for values in $config corresponding to the keys specified and copies them, if defined, into $self. Keys can be specified in UPPER CASE and the method will look for either upper or lower case equivalents in the C<$config> hash. Thus you can call C from C like so: sub init { my ($self, $config) = @_; $self->params($config, qw( FOO BAR )) return $self; } but use either case for parameters passed to C: my $object = My::Module->new( FOO => 'the foo value', BAR => 'the bar value' ) || die My::Module->error(); my $object = My::Module->new( foo => 'the foo value', bar => 'the bar value' ) || die My::Module->error(); Note however that the internal key within C<$self> used to store the value will be in the case provided in the call to C (upper case in this example). The method doesn't look for upper case equivalents when they are specified in lower case. When called in list context, the method returns a list of all the values corresponding to the list of keys, some of which may be undefined (allowing you to determine which values were successfully set if you need to). When called in scalar context it returns a reference to the same list. =head2 clone() The C method performs a simple shallow copy of the object hash and creates a new object blessed into the same class. You may want to provide your own C method to perform a more complex cloning operation. my $clone = $object->clone(); =head2 error($msg, ...) General purpose method for getting and setting error messages. When called as a class method, it returns the value of the C<$ERROR> package variable (in the derived class' package) if called without any arguments, or sets the same variable when called with one or more arguments. Multiple arguments are concatenated together. # set error My::Module->error('set the error string'); My::Module->error('set ', 'the ', 'error string'); # get error print My::Module->error(); print $My::Module::ERROR; When called as an object method, it operates on the C<_ERROR> member of the object, returning it when called without any arguments, or setting it when called with arguments. # set error $object->error('set the error string'); # get error print $object->error(); The method returns C when called with arguments. This allows it to be used within object methods as shown: sub my_method { my $self = shift; # set error and return undef in one return $self->error('bad, bad, error') if $something_bad; } =head2 debug($msg, $msg, ...) Prints all arguments to STDERR if the internal C<_DEBUG> flag (when called as an object method) or C<$DEBUG> package variable (when called as a class method) is set to a true value. Otherwise does nothing. The output is prefixed by a string of the form "[Class::Name]" where the name of the class is that returned by the C method. =head2 debugging($flag) Used to get (no arguments) or set ($flag defined) the value of the internal C<_DEBUG> flag (when called as an object method) or C<$DEBUG> package variable (when called as a class method). =head2 id($newid) The C method calls this method to return an identifier for the object for printing in the debugging message. By default it returns the class name of the object (i.e. C), but you can of course subclass the method to return some other value. When called with an argument it uses that value to set its internal C<_ID> field which will be returned by subsequent calls to C. =head1 HISTORY This module began life as the Template::Base module distributed as part of the Template Toolkit. Thanks to Brian Moseley and Matt Sergeant for suggesting various enhancements, some of which went into version 0.02. Version 0.04 was uploaded by Gabor Szabo. =head1 AUTHORS =over 4 =item * Andy Wardley =item * Gabor Szabo =item * Yanick Champoux =back =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2018, 2016, 2014, 2012 by Andy Wardley. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut Class-Base-0.09/Makefile.PL0000644000175000017500000000263213223464640014656 0ustar yanickyanick# This file was automatically generated by Dist::Zilla::Plugin::MakeMaker v6.009. use strict; use warnings; use 5.006; use ExtUtils::MakeMaker; my %WriteMakefileArgs = ( "ABSTRACT" => "useful base class for deriving other modules ", "AUTHOR" => "Andy Wardley , Gabor Szabo , Yanick Champoux ", "CONFIGURE_REQUIRES" => { "ExtUtils::MakeMaker" => 0 }, "DISTNAME" => "Class-Base", "LICENSE" => "perl", "MIN_PERL_VERSION" => "5.006", "NAME" => "Class::Base", "PREREQ_PM" => { "Clone" => 0, "strict" => 0, "warnings" => 0 }, "TEST_REQUIRES" => { "ExtUtils::MakeMaker" => 0, "File::Spec" => 0, "IO::Handle" => 0, "IPC::Open3" => 0, "Test::More" => 0, "base" => 0, "vars" => 0 }, "VERSION" => "0.09", "test" => { "TESTS" => "t/*.t" } ); my %FallbackPrereqs = ( "Clone" => 0, "ExtUtils::MakeMaker" => 0, "File::Spec" => 0, "IO::Handle" => 0, "IPC::Open3" => 0, "Test::More" => 0, "base" => 0, "strict" => 0, "vars" => 0, "warnings" => 0 ); unless ( eval { ExtUtils::MakeMaker->VERSION(6.63_03) } ) { delete $WriteMakefileArgs{TEST_REQUIRES}; delete $WriteMakefileArgs{BUILD_REQUIRES}; $WriteMakefileArgs{PREREQ_PM} = \%FallbackPrereqs; } delete $WriteMakefileArgs{CONFIGURE_REQUIRES} unless eval { ExtUtils::MakeMaker->VERSION(6.52) }; WriteMakefile(%WriteMakefileArgs); Class-Base-0.09/MANIFEST0000644000175000017500000000037213223464640014034 0ustar yanickyanickCONTRIBUTORS Changes INSTALL LICENSE MANIFEST META.json META.yml Makefile.PL README README.mkdn SIGNATURE TODO cpanfile dist.ini doap.xml lib/Class/Base.pm t/00-compile.t t/00-report-prereqs.dd t/00-report-prereqs.t t/test.t xt/release/unused-vars.t Class-Base-0.09/Changes0000644000175000017500000000241213223464640014173 0ustar yanickyanick Revision history for the Class::Base module 0.09 2018-01-04 [ DOCUMENTATION ] - Fix pod typo. (GH#4, knowledgejunkie) [ ENHANCEMENTS ] - clone method now deep clone. - a few minor refactorings. [ STATISTICS ] - code churn: 9 files changed, 139 insertions(+), 137 deletions(-) 0.08 2016 .08.25 - Fix release (hopefully) 0.07 2016 .08.25 - BUILD_REQUIRES vs TEST_REQUIRES (Kent Fredric) 0.06 2014 .08.26 - Add license to META files - Updating the Changes file 0.05 2012 .05.16 - Silencing a warning by chromatic RT 75286 - Linking to source repository 0.04 2012 .02.06 - Test script is using Test::More instead the home-made ok() and is(). - Recommend using Badger::Base instead. - Gabor Szabo co-maintainer. 0.03 2002 .05.13 - Added the params() method which is typically called from the init() method to copy value from a configuration hash into $self. - Minor changes to debug() method to only use object value _DEBUG if defined, otherwise fall back on $DEBUG package variable. 0.02 2002 .02.20 - Added the clone() method as suggested by Brian Moseley - Added the id(), debug() and debugging() methods to provide a fairly simple mechanism for generating debugging information. 0.01 2002 .01.11 - initial version Class-Base-0.09/LICENSE0000644000175000017500000004374313223464640013721 0ustar yanickyanickThis software is copyright (c) 2018, 2016, 2014, 2012 by Andy Wardley. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2018, 2016, 2014, 2012 by Andy Wardley. This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2018, 2016, 2014, 2012 by Andy Wardley. This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End Class-Base-0.09/README.mkdn0000644000175000017500000004026513223464640014520 0ustar yanickyanick# NAME Class::Base - useful base class for deriving other modules # VERSION version 0.09 # SYNOPSIS ```perl package My::Funky::Module; use base qw( Class::Base ); # custom initialiser method sub init { my ($self, $config) = @_; # copy various params into $self $self->params($config, qw( FOO BAR BAZ )) || return undef; # to indicate a failure return $self->error('bad constructor!') if $something_bad; # or to indicate general happiness and well-being return $self; } package main; # new() constructor folds args into hash and calls init() my $object = My::Funky::Module->new( foo => 'bar', ... ) || die My::Funky::Module->error(); # error() class/object method to get/set errors $object->error('something has gone wrong'); print $object->error(); # debugging() method (de-)activates the debug() method $object->debugging(1); # debug() prints to STDERR if debugging enabled $object->debug('The ', $animal, ' sat on the ', $place); ``` # DESCRIPTION Please consider using [Badger::Base](https://metacpan.org/pod/Badger::Base) instead which is the successor of this module. This module implements a simple base class from which other modules can be derived, thereby inheriting a number of useful methods such as `new()`, `init()`, `params()`, `clone()`, `error()` and `debug()`. For a number of years, I found myself re-writing this module for practically every Perl project of any significant size. Or rather, I would copy the module from the last project and perform a global search and replace to change the names. Each time it got a little more polished and eventually, I decided to Do The Right Thing and release it as a module in it's own right. It doesn't pretend to be an all-encompassing solution for every kind of object creation problem you might encounter. In fact, it only supports blessed hash references that are created using the popular, but by no means universal convention of calling `new()` with a list or reference to a hash array of named parameters. Constructor failure is indicated by returning undef and setting the `$ERROR` package variable in the module's class to contain a relevant message (which you can also fetch by calling `error()` as a class method). e.g. ```perl my $object = My::Module->new( file => 'myfile.html', msg => 'Hello World' ) || die $My::Module::ERROR; ``` or: ```perl my $object = My::Module->new({ file => 'myfile.html', msg => 'Hello World', }) || die My::Module->error(); ``` The `new()` method handles the conversion of a list of arguments into a hash array and calls the `init()` method to perform any initialisation. In many cases, it is therefore sufficient to define a module like so: ```perl package My::Module; use Class::Base; use base qw( Class::Base ); sub init { my ($self, $config) = @_; # copy some config items into $self $self->params($config, qw( FOO BAR )) || return undef; return $self; } # ...plus other application-specific methods 1; ``` Then you can go right ahead and use it like this: ```perl use My::Module; my $object = My::Module->new( FOO => 'the foo value', BAR => 'the bar value' ) || die $My::Module::ERROR; ``` Despite its limitations, Class::Base can be a surprisingly useful module to have lying around for those times where you just want to create a regular object based on a blessed hash reference and don't want to worry too much about duplicating the same old code to bless a hash, define configuration values, provide an error reporting mechanism, and so on. Simply derive your module from `Class::Base` and leave it to worry about most of the detail. And don't forget, you can always redefine your own `new()`, `error()`, or other method, if you don't like the way the Class::Base version works. ## Subclassing Class::Base This module is what object-oriented afficionados would describe as an "abstract base class". That means that it's not designed to be used as a stand-alone module, rather as something from which you derive your own modules. Like this: ```perl package My::Funky::Module use base qw( Class::Base ); ``` You can then use it like this: ```perl use My::Funky::Module; my $module = My::Funky::Module->new(); ``` ## Construction and Initialisation Methods If you want to apply any per-object initialisation, then simply write an `init()` method. This gets called by the `new()` method which passes a reference to a hash reference of configuration options. ```perl sub init { my ($self, $config) = @_; ... return $self; } ``` When you create new objects using the `new()` method you can either pass a hash reference or list of named arguments. The `new()` method does the right thing to fold named arguments into a hash reference for passing to the `init()` method. Thus, the following are equivalent: ```perl # hash reference my $module = My::Funky::Module->new({ foo => 'bar', wiz => 'waz', }); # list of named arguments (no enclosing '{' ... '}') my $module = My::Funky::Module->new( foo => 'bar', wiz => 'waz' ); ``` Within the `init()` method, you can either handle the configuration yourself: ```perl sub init { my ($self, $config) = @_; $self->{ file } = $config->{ file } || return $self->error('no file specified'); return $self; } ``` or you can call the `params()` method to do it for you: ```perl sub init { my ($self, $config) = @_; $self->params($config, 'file') || return $self->error('no file specified'); return $self; } ``` ## Error Handling The `init()` method should return $self to indicate success or undef to indicate a failure. You can use the `error()` method to report an error within the `init()` method. The `error()` method returns undef, so you can use it like this: ```perl sub init { my ($self, $config) = @_; # let's make 'foobar' a mandatory argument $self->{ foobar } = $config->{ foobar } || return $self->error("no foobar argument"); return $self; } ``` When you create objects of this class via `new()`, you should now check the return value. If undef is returned then the error message can be retrieved by calling `error()` as a class method. ```perl my $module = My::Funky::Module->new() || die My::Funky::Module->error(); ``` Alternately, you can inspect the `$ERROR` package variable which will contain the same error message. ```perl my $module = My::Funky::Module->new() || die $My::Funky::Module::ERROR; ``` Of course, being a conscientious Perl programmer, you will want to be sure that the `$ERROR` package variable is correctly defined. ```perl package My::Funky::Module use base qw( Class::Base ); our $ERROR; ``` You can also call `error()` as an object method. If you pass an argument then it will be used to set the internal error message for the object and return undef. Typically this is used within the module methods to report errors. ```perl sub another_method { my $self = shift; ... # set the object error return $self->error('something bad happened'); } ``` If you don't pass an argument then the `error()` method returns the current error value. Typically this is called from outside the object to determine its status. For example: ```perl my $object = My::Funky::Module->new() || die My::Funky::Module->error(); $object->another_method() || die $object->error(); ``` ## Debugging Methods The module implements two methods to assist in writing debugging code: debug() and debugging(). Debugging can be enabled on a per-object or per-class basis, or as a combination of the two. When creating an object, you can set the `DEBUG` flag (or lower case `debug` if you prefer) to enable or disable debugging for that one object. ```perl my $object = My::Funky::Module->new( debug => 1 ) || die My::Funky::Module->error(); my $object = My::Funky::Module->new( DEBUG => 1 ) || die My::Funky::Module->error(); ``` If you don't explicitly specify a debugging flag then it assumes the value of the `$DEBUG` package variable in your derived class or 0 if that isn't defined. You can also switch debugging on or off via the `debugging()` method. ``` $object->debugging(0); # debug off $object->debugging(1); # debug on ``` The `debug()` method examines the internal debugging flag (the `_DEBUG` member within the `$self` hash) and if it finds it set to any true value then it prints to STDERR all the arguments passed to it. The output is prefixed by a tag containing the class name of the object in square brackets (but see the `id()` method below for details on how to change that value). For example, calling the method as: ``` $object->debug('foo', 'bar'); ``` prints the following output to STDERR: ``` [My::Funky::Module] foobar ``` When called as class methods, `debug()` and `debugging()` instead use the `$DEBUG` package variable in the derived class as a flag to control debugging. This variable also defines the default `DEBUG` flag for any objects subsequently created via the new() method. ```perl package My::Funky::Module use base qw( Class::Base ); our $ERROR; our $DEBUG = 0 unless defined $DEBUG; # some time later, in a module far, far away package main; # debugging off (by default) my $object1 = My::Funky::Module->new(); # turn debugging on for My::Funky::Module objects $My::Funky::Module::DEBUG = 1; # alternate syntax My::Funky::Module->debugging(1); # debugging on (implicitly from $DEBUG package var) my $object2 = My::Funky::Module->new(); # debugging off (explicit override) my $object3 = My::Funky::Module->new(debug => 0); ``` If you call `debugging()` without any arguments then it returns the value of the internal object flag or the package variable accordingly. ``` print "debugging is turned ", $object->debugging() ? 'on' : 'off'; ``` # METHODS ## new() Class constructor method which expects a reference to a hash array of parameters or a list of `name => value` pairs which are automagically folded into a hash reference. The method blesses a hash reference and then calls the `init()` method, passing the reference to the hash array of configuration parameters. Returns a reference to an object on success or undef on error. In the latter case, the `error()` method can be called as a class method, or the `$ERROR` package variable (in the derived class' package) can be inspected to return an appropriate error message. ```perl my $object = My::Class->new( foo => 'bar' ) # params list || die $My::Class::$ERROR; # package var ``` or ```perl my $object = My::Class->new({ foo => 'bar' }) # params hashref || die My::Class->error; # class method ``` ## init(\\%config) Object initialiser method which is called by the `new()` method, passing a reference to a hash array of configuration parameters. The method may be derived in a subclass to perform any initialisation required. It should return `$self` on success, or `undef` on error, via a call to the `error()` method. ```perl package My::Module; use base qw( Class::Base ); sub init { my ($self, $config) = @_; # let's make 'foobar' a mandatory argument $self->{ foobar } = $config->{ foobar } || return $self->error("no foobar argument"); return $self; } ``` ## params($config, @keys) The `params()` method accept a reference to a hash array as the first argument containing configuration values such as those passed to the `init()` method. The second argument can be a reference to a list of parameter names or a reference to a hash array mapping parameter names to default values. If the second argument is not a reference then all the remaining arguments are taken as parameter names. Thus the method can be called as follows: ```perl sub init { my ($self, $config) = @_; # either... $self->params($config, qw( foo bar )); # or... $self->params($config, [ qw( foo bar ) ]); # or... $self->params($config, { foo => 'default foo value', bar => 'default bar value' } ); return $self; } ``` The method looks for values in $config corresponding to the keys specified and copies them, if defined, into $self. Keys can be specified in UPPER CASE and the method will look for either upper or lower case equivalents in the `$config` hash. Thus you can call `params()` from `init()` like so: ```perl sub init { my ($self, $config) = @_; $self->params($config, qw( FOO BAR )) return $self; } ``` but use either case for parameters passed to `new()`: ```perl my $object = My::Module->new( FOO => 'the foo value', BAR => 'the bar value' ) || die My::Module->error(); my $object = My::Module->new( foo => 'the foo value', bar => 'the bar value' ) || die My::Module->error(); ``` Note however that the internal key within `$self` used to store the value will be in the case provided in the call to `params()` (upper case in this example). The method doesn't look for upper case equivalents when they are specified in lower case. When called in list context, the method returns a list of all the values corresponding to the list of keys, some of which may be undefined (allowing you to determine which values were successfully set if you need to). When called in scalar context it returns a reference to the same list. ## clone() The `clone()` method performs a simple shallow copy of the object hash and creates a new object blessed into the same class. You may want to provide your own `clone()` method to perform a more complex cloning operation. ```perl my $clone = $object->clone(); ``` ## error($msg, ...) General purpose method for getting and setting error messages. When called as a class method, it returns the value of the `$ERROR` package variable (in the derived class' package) if called without any arguments, or sets the same variable when called with one or more arguments. Multiple arguments are concatenated together. ``` # set error My::Module->error('set the error string'); My::Module->error('set ', 'the ', 'error string'); # get error print My::Module->error(); print $My::Module::ERROR; ``` When called as an object method, it operates on the `_ERROR` member of the object, returning it when called without any arguments, or setting it when called with arguments. ``` # set error $object->error('set the error string'); # get error print $object->error(); ``` The method returns `undef` when called with arguments. This allows it to be used within object methods as shown: ```perl sub my_method { my $self = shift; # set error and return undef in one return $self->error('bad, bad, error') if $something_bad; } ``` ## debug($msg, $msg, ...) Prints all arguments to STDERR if the internal `_DEBUG` flag (when called as an object method) or `$DEBUG` package variable (when called as a class method) is set to a true value. Otherwise does nothing. The output is prefixed by a string of the form "\[Class::Name\]" where the name of the class is that returned by the `id()` method. ## debugging($flag) Used to get (no arguments) or set ($flag defined) the value of the internal `_DEBUG` flag (when called as an object method) or `$DEBUG` package variable (when called as a class method). ## id($newid) The `debug()` method calls this method to return an identifier for the object for printing in the debugging message. By default it returns the class name of the object (i.e. `ref $self`), but you can of course subclass the method to return some other value. When called with an argument it uses that value to set its internal `_ID` field which will be returned by subsequent calls to `id()`. # HISTORY This module began life as the Template::Base module distributed as part of the Template Toolkit. Thanks to Brian Moseley and Matt Sergeant for suggesting various enhancements, some of which went into version 0.02. Version 0.04 was uploaded by Gabor Szabo. # AUTHORS - Andy Wardley - Gabor Szabo - Yanick Champoux [![endorse](http://api.coderwall.com/yanick/endorsecount.png)](http://coderwall.com/yanick) # COPYRIGHT AND LICENSE This software is copyright (c) 2018, 2016, 2014, 2012 by Andy Wardley. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Class-Base-0.09/SIGNATURE0000644000175000017500000000350113223464640014164 0ustar yanickyanickThis file contains message digests of all files listed in MANIFEST, signed via the Module::Signature module, version 0.79. To verify the content in this distribution, first make sure you have Module::Signature installed, then type: % cpansign -v It will check each file's integrity, as well as the signature's validity. If "==> Signature verified OK! <==" is not displayed, the distribution may already have been compromised, and you should not run its Makefile.PL or Build.PL. -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 SHA1 752bff970d8a4e642430da8f5eacb06067c1530f CONTRIBUTORS SHA1 e59d6432ce9f5ad709a7da093ad7afccecd39309 Changes SHA1 573f790f1149698011dbc6f7299f75d39e6f0bcb INSTALL SHA1 9102d582aed83299d9d5526f94af9fbacd0ca776 LICENSE SHA1 2273d2094dab5187866cebcddbb984104e09ccb2 MANIFEST SHA1 66411fea20648a55a47314a1758f72027b10ae33 META.json SHA1 d805b5a7c04d71016ea6343138ebc26fbfbd7bb1 META.yml SHA1 64c919b98ae183a42d3ec84fa5efc1f184fce90f Makefile.PL SHA1 fdcd2de21dbbb530ef11aeeb46675d0154cf05ef README SHA1 cdd4b071fed4ee98efeb72d068a0016d5f922fa9 README.mkdn SHA1 48a5228c9adaf19f077f9231b9ab7cdfa8126424 TODO SHA1 971162b5497a7368a96e02a98867b22bcc92d00a cpanfile SHA1 d6891e6d5edd5d21c812c4ce422a91f5a6ea2ae6 dist.ini SHA1 3f715939f6de5667db612185a9e74bb3ed311fe0 doap.xml SHA1 ddd0d3920d4881077782b751731095fbb2e4c641 lib/Class/Base.pm SHA1 f0a0c939e3322eb9e5d4cfa7dde78ddf0f75c606 t/00-compile.t SHA1 36cfccfd7792fb4c16e70463cd7bae2cf4d1a323 t/00-report-prereqs.dd SHA1 504a672015f8761f5bad3863d844954c9e803c3f t/00-report-prereqs.t SHA1 baf9b5335f5474c9c3e614018e81176b1f1a1721 t/test.t SHA1 d1fe7d94b3edc7847eb187d4ee41f66e19cf8907 xt/release/unused-vars.t -----BEGIN PGP SIGNATURE----- iEYEARECAAYFAlpOaaAACgkQ34Hwf+GwC4xTQQCgs3kT1elwxt67w4uS5Um7A0w4 PCkAoMvwrgBbY15/KtZzq6yHdVXsOlSd =i2e5 -----END PGP SIGNATURE----- Class-Base-0.09/INSTALL0000644000175000017500000000165313223464640013737 0ustar yanickyanickThis is the Perl distribution Class-Base. Installing Class-Base is straightforward. ## Installation with cpanm If you have cpanm, you only need one line: % cpanm Class::Base If you are installing into a system-wide directory, you may need to pass the "-S" flag to cpanm, which uses sudo to install the module: % cpanm -S Class::Base ## Installing with the CPAN shell Alternatively, if your CPAN shell is set up, you should just be able to do: % cpan Class::Base ## Manual installation As a last resort, you can manually install it. Download the tarball, untar it, then build it: % perl Makefile.PL % make && make test Then install it: % make install If you are installing into a system-wide directory, you may need to run: % sudo make install ## Documentation Class-Base documentation is available as POD. You can run perldoc from a shell to read the documentation: % perldoc Class::Base Class-Base-0.09/CONTRIBUTORS0000644000175000017500000000051213223464640014557 0ustar yanickyanick # CLASS-BASE CONTRIBUTORS # This is the (likely incomplete) list of people who have helped make this distribution what it is, either via code contributions, patches, bug reports, help with troubleshooting, etc. A huge 'thank you' to all of them. * Gabor Szabo * Kent Fredric * Nick Morrott * Yanick Champoux Class-Base-0.09/META.json0000644000175000017500000000412613223464640014325 0ustar yanickyanick{ "abstract" : "useful base class for deriving other modules ", "author" : [ "Andy Wardley ", "Gabor Szabo ", "Yanick Champoux " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.009, CPAN::Meta::Converter version 2.150001", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Class-Base", "prereqs" : { "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "develop" : { "requires" : { "Test::More" : "0.96", "Test::Vars" : "0" } }, "runtime" : { "requires" : { "Clone" : "0", "strict" : "0", "warnings" : "0" } }, "test" : { "recommends" : { "CPAN::Meta" : "2.120900" }, "requires" : { "ExtUtils::MakeMaker" : "0", "File::Spec" : "0", "IO::Handle" : "0", "IPC::Open3" : "0", "Test::More" : "0", "base" : "0", "perl" : "5.006", "vars" : "0" } } }, "provides" : { "Class::Base" : { "file" : "lib/Class/Base.pm", "version" : "0.09" } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/yanick/Class-Base/issues" }, "homepage" : "https://github.com/yanick/Class-Base", "repository" : { "type" : "git", "url" : "https://github.com/yanick/Class-Base.git", "web" : "https://github.com/yanick/Class-Base" } }, "version" : "0.09", "x_authority" : "cpan:YANICK", "x_contributors" : [ "Gabor Szabo ", "Kent Fredric ", "Nick Morrott ", "Yanick Champoux " ], "x_serialization_backend" : "JSON::XS version 3.01" } Class-Base-0.09/META.yml0000644000175000017500000000225013223464640014151 0ustar yanickyanick--- abstract: 'useful base class for deriving other modules ' author: - 'Andy Wardley ' - 'Gabor Szabo ' - 'Yanick Champoux ' build_requires: ExtUtils::MakeMaker: '0' File::Spec: '0' IO::Handle: '0' IPC::Open3: '0' Test::More: '0' base: '0' perl: '5.006' vars: '0' configure_requires: ExtUtils::MakeMaker: '0' dynamic_config: 0 generated_by: 'Dist::Zilla version 6.009, CPAN::Meta::Converter version 2.150001' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Class-Base provides: Class::Base: file: lib/Class/Base.pm version: '0.09' requires: Clone: '0' strict: '0' warnings: '0' resources: bugtracker: https://github.com/yanick/Class-Base/issues homepage: https://github.com/yanick/Class-Base repository: https://github.com/yanick/Class-Base.git version: '0.09' x_authority: cpan:YANICK x_contributors: - 'Gabor Szabo ' - 'Kent Fredric ' - 'Nick Morrott ' - 'Yanick Champoux ' x_serialization_backend: 'YAML::Tiny version 1.67' Class-Base-0.09/cpanfile0000644000175000017500000000110313223464640014400 0ustar yanickyanickrequires "Clone" => "0"; requires "strict" => "0"; requires "warnings" => "0"; on 'test' => sub { requires "ExtUtils::MakeMaker" => "0"; requires "File::Spec" => "0"; requires "IO::Handle" => "0"; requires "IPC::Open3" => "0"; requires "Test::More" => "0"; requires "base" => "0"; requires "perl" => "5.006"; requires "vars" => "0"; }; on 'test' => sub { recommends "CPAN::Meta" => "2.120900"; }; on 'configure' => sub { requires "ExtUtils::MakeMaker" => "0"; }; on 'develop' => sub { requires "Test::More" => "0.96"; requires "Test::Vars" => "0"; }; Class-Base-0.09/t/0000775000175000017500000000000013223464640013146 5ustar yanickyanickClass-Base-0.09/t/00-report-prereqs.t0000644000175000017500000001273113223464640016544 0ustar yanickyanick#!perl use strict; use warnings; # This test was generated by Dist::Zilla::Plugin::Test::ReportPrereqs 0.021 use Test::More tests => 1; use ExtUtils::MakeMaker; use File::Spec; # from $version::LAX my $lax_version_re = qr/(?: undef | (?: (?:[0-9]+) (?: \. | (?:\.[0-9]+) (?:_[0-9]+)? )? | (?:\.[0-9]+) (?:_[0-9]+)? ) | (?: v (?:[0-9]+) (?: (?:\.[0-9]+)+ (?:_[0-9]+)? )? | (?:[0-9]+)? (?:\.[0-9]+){2,} (?:_[0-9]+)? ) )/x; # hide optional CPAN::Meta modules from prereq scanner # and check if they are available my $cpan_meta = "CPAN::Meta"; my $cpan_meta_pre = "CPAN::Meta::Prereqs"; my $HAS_CPAN_META = eval "require $cpan_meta; $cpan_meta->VERSION('2.120900')" && eval "require $cpan_meta_pre"; ## no critic # Verify requirements? my $DO_VERIFY_PREREQS = 1; sub _max { my $max = shift; $max = ( $_ > $max ) ? $_ : $max for @_; return $max; } sub _merge_prereqs { my ($collector, $prereqs) = @_; # CPAN::Meta::Prereqs object if (ref $collector eq $cpan_meta_pre) { return $collector->with_merged_prereqs( CPAN::Meta::Prereqs->new( $prereqs ) ); } # Raw hashrefs for my $phase ( keys %$prereqs ) { for my $type ( keys %{ $prereqs->{$phase} } ) { for my $module ( keys %{ $prereqs->{$phase}{$type} } ) { $collector->{$phase}{$type}{$module} = $prereqs->{$phase}{$type}{$module}; } } } return $collector; } my @include = qw( ); my @exclude = qw( ); # Add static prereqs to the included modules list my $static_prereqs = do 't/00-report-prereqs.dd'; # Merge all prereqs (either with ::Prereqs or a hashref) my $full_prereqs = _merge_prereqs( ( $HAS_CPAN_META ? $cpan_meta_pre->new : {} ), $static_prereqs ); # Add dynamic prereqs to the included modules list (if we can) my ($source) = grep { -f } 'MYMETA.json', 'MYMETA.yml'; if ( $source && $HAS_CPAN_META ) { if ( my $meta = eval { CPAN::Meta->load_file($source) } ) { $full_prereqs = _merge_prereqs($full_prereqs, $meta->prereqs); } } else { $source = 'static metadata'; } my @full_reports; my @dep_errors; my $req_hash = $HAS_CPAN_META ? $full_prereqs->as_string_hash : $full_prereqs; # Add static includes into a fake section for my $mod (@include) { $req_hash->{other}{modules}{$mod} = 0; } for my $phase ( qw(configure build test runtime develop other) ) { next unless $req_hash->{$phase}; next if ($phase eq 'develop' and not $ENV{AUTHOR_TESTING}); for my $type ( qw(requires recommends suggests conflicts modules) ) { next unless $req_hash->{$phase}{$type}; my $title = ucfirst($phase).' '.ucfirst($type); my @reports = [qw/Module Want Have/]; for my $mod ( sort keys %{ $req_hash->{$phase}{$type} } ) { next if $mod eq 'perl'; next if grep { $_ eq $mod } @exclude; my $file = $mod; $file =~ s{::}{/}g; $file .= ".pm"; my ($prefix) = grep { -e File::Spec->catfile($_, $file) } @INC; my $want = $req_hash->{$phase}{$type}{$mod}; $want = "undef" unless defined $want; $want = "any" if !$want && $want == 0; my $req_string = $want eq 'any' ? 'any version required' : "version '$want' required"; if ($prefix) { my $have = MM->parse_version( File::Spec->catfile($prefix, $file) ); $have = "undef" unless defined $have; push @reports, [$mod, $want, $have]; if ( $DO_VERIFY_PREREQS && $HAS_CPAN_META && $type eq 'requires' ) { if ( $have !~ /\A$lax_version_re\z/ ) { push @dep_errors, "$mod version '$have' cannot be parsed ($req_string)"; } elsif ( ! $full_prereqs->requirements_for( $phase, $type )->accepts_module( $mod => $have ) ) { push @dep_errors, "$mod version '$have' is not in required range '$want'"; } } } else { push @reports, [$mod, $want, "missing"]; if ( $DO_VERIFY_PREREQS && $type eq 'requires' ) { push @dep_errors, "$mod is not installed ($req_string)"; } } } if ( @reports ) { push @full_reports, "=== $title ===\n\n"; my $ml = _max( map { length $_->[0] } @reports ); my $wl = _max( map { length $_->[1] } @reports ); my $hl = _max( map { length $_->[2] } @reports ); if ($type eq 'modules') { splice @reports, 1, 0, ["-" x $ml, "", "-" x $hl]; push @full_reports, map { sprintf(" %*s %*s\n", -$ml, $_->[0], $hl, $_->[2]) } @reports; } else { splice @reports, 1, 0, ["-" x $ml, "-" x $wl, "-" x $hl]; push @full_reports, map { sprintf(" %*s %*s %*s\n", -$ml, $_->[0], $wl, $_->[1], $hl, $_->[2]) } @reports; } push @full_reports, "\n"; } } } if ( @full_reports ) { diag "\nVersions for all modules listed in $source (including optional ones):\n\n", @full_reports; } if ( @dep_errors ) { diag join("\n", "\n*** WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING ***\n", "The following REQUIRED prerequisites were not satisfied:\n", @dep_errors, "\n" ); } pass; # vim: ts=4 sts=4 sw=4 et: Class-Base-0.09/t/00-report-prereqs.dd0000644000175000017500000000264513223464640016673 0ustar yanickyanickdo { my $x = { 'configure' => { 'requires' => { 'ExtUtils::MakeMaker' => '0' } }, 'develop' => { 'requires' => { 'Test::More' => '0.96', 'Test::Vars' => '0' } }, 'runtime' => { 'requires' => { 'Clone' => '0', 'strict' => '0', 'warnings' => '0' } }, 'test' => { 'recommends' => { 'CPAN::Meta' => '2.120900' }, 'requires' => { 'ExtUtils::MakeMaker' => '0', 'File::Spec' => '0', 'IO::Handle' => '0', 'IPC::Open3' => '0', 'Test::More' => '0', 'base' => '0', 'perl' => '5.006', 'vars' => '0' } } }; $x; }Class-Base-0.09/t/00-compile.t0000644000175000017500000000211613223464640015176 0ustar yanickyanickuse 5.006; use strict; use warnings; # this test was generated with Dist::Zilla::Plugin::Test::Compile 2.052 use Test::More; plan tests => 1 + ($ENV{AUTHOR_TESTING} ? 1 : 0); my @module_files = ( 'Class/Base.pm' ); # no fake home requested my $inc_switch = -d 'blib' ? '-Mblib' : '-Ilib'; use File::Spec; use IPC::Open3; use IO::Handle; open my $stdin, '<', File::Spec->devnull or die "can't open devnull: $!"; my @warnings; for my $lib (@module_files) { # see L my $stderr = IO::Handle->new; my $pid = open3($stdin, '>&STDERR', $stderr, $^X, $inc_switch, '-e', "require q[$lib]"); binmode $stderr, ':crlf' if $^O eq 'MSWin32'; my @_warnings = <$stderr>; waitpid($pid, 0); is($?, 0, "$lib loaded ok"); if (@_warnings) { warn @_warnings; push @warnings, @_warnings; } } is(scalar(@warnings), 0, 'no warnings found') or diag 'got warnings: ', ( Test::More->can('explain') ? Test::More::explain(\@warnings) : join("\n", '', @warnings) ) if $ENV{AUTHOR_TESTING}; Class-Base-0.09/t/test.t0000755000175000017500000002432313223464640014317 0ustar yanickyanick#!/usr/bin/perl -w # -*- perl -*- #======================================================================== # # test.pl # # Test the Class::Base.pm module. # # Written by Andy Wardley , based on the version lifted from # the Template Toolkit. # # This is free software; you can redistribute it and/or modify it # under the same terms as Perl itself. # #======================================================================== use strict; use warnings; use Class::Base; #------------------------------------------------------------------------ # mini test harness #------------------------------------------------------------------------ use Test::More tests => 45; #------------------------------------------------------------------------ # quick hack to allow STDERR to be tied to a variable. #------------------------------------------------------------------------ package Tie::File2Str; sub TIEHANDLE { my ($class, $textref) = @_; bless $textref, $class; } sub PRINT { my $self = shift; $$self .= join('', @_); } package main; # tie STDERR to a variable my $stderr = ''; tie(*STDERR, "Tie::File2Str", \$stderr); #------------------------------------------------------------------------ # Class::Test::Fail always fails, but we check it reports errors OK #------------------------------------------------------------------------ package Class::Test::Fail; use base qw( Class::Base ); use vars qw( $ERROR ); sub init { my $self = shift; return $self->error('expected failure'); } package main; my ($pkg, $mod); # instantiate a base class object and test error reporting/returning $mod = Class::Base->new(); ok( $mod ); ok( ! defined $mod->error('barf') ); ok( $mod->error() eq 'barf' ); # Class::Test::Fail should never work, but we check it reports errors OK $pkg = 'Class::Test::Fail'; ok( ! $pkg->new() ); is( $pkg->error, 'expected failure' ); is( $Class::Test::Fail::ERROR, 'expected failure' ); #------------------------------------------------------------------------ # Class::Test::Name should only work with a 'name'parameters #------------------------------------------------------------------------ package Class::Test::Name; use base qw( Class::Base ); use vars qw( $ERROR ); sub init { my ($self, $params) = @_; $self->{ NAME } = $params->{ name } || return $self->error("No name!"); return $self; } sub name { $_[0]->{ NAME }; } package main; $mod = Class::Test::Name->new(); ok( ! $mod ); is( $Class::Test::Name::ERROR, 'No name!' ); is( Class::Test::Name->error(), 'No name!' ); # give it what it wants... $mod = Class::Test::Name->new({ name => 'foo' }); ok( $mod ); ok( ! $mod->error() ); is( $mod->name(), 'foo' ); # ... in 2 different flavours $mod = Class::Test::Name->new(name => 'foo'); ok( $mod ); ok( ! $mod->error() ); is( $mod->name(), 'foo' ); subtest 'clone() method' => sub { my $clone = $mod->clone; ok $mod ; ok ! $mod->error ; is $mod->name, 'foo', 'clone is ok'; subtest 'deep cloning' => sub { my $mod = Class::Test::Name->new( name => { a => 'ref' } ); my $clone = $mod->clone; $clone->name->{a} = 'changed ref'; is $clone->name->{a}, 'changed ref', "the clone changes"; is $mod->name->{a}, 'ref', "the original didn't change"; }; }; subtest 'id method and constructor parameters' => sub { my $obj = Class::Base->new(); ok( $obj ); ok( $obj->id eq 'Class::Base' ); ok( $obj->id('foo') eq 'foo' ); $obj = Class::Base->new( ID => 'foo' ); ok( $obj ); ok( $obj->id eq 'foo' ); $obj = Class::Base->new( id => 'bar' ); ok( $obj ); ok( $obj->id eq 'bar' ); ok( $obj->id('baz') eq 'baz' ); ok( $obj->id eq 'baz' ); package My::Class::Base; use base qw( Class::Base ); our $DEBUG; package main; $obj = My::Class::Base->new( ); ok( $obj ); ok( $obj->id() eq 'My::Class::Base' ); $obj = My::Class::Base->new( ID => 'wiz', DEBUG => 1 ); ok( $obj ); ok( $obj->id() eq 'wiz' ); $stderr = ''; $obj->debug('hello world'); ok( $stderr eq '[wiz] hello world' ) or print "stderr is [$stderr] not '[wiz] hello world'\n"; }; subtest 'debugging method and params' => sub { my $obj = Class::Base->new( ); ok( $obj, 'debugging object created' ); ok( ! $obj->debugging ); ok( $obj->debugging(1) ); ok( $obj->debugging ); $obj = Class::Base->new( debug => 1 ); ok( $obj ); ok( $obj->debugging ); ok( ! $obj->debugging(0) ); ok( ! $obj->debugging ); $obj = Class::Base->new( DEBUG => 1 ); ok( $obj ); ok( $obj->debugging ); ok( ! $obj->debugging(0) ); ok( ! $obj->debugging ); $obj = My::Class::Base->new( ); ok( $obj ); ok( ! $obj->debugging ); ok( ! $My::Class::Base::DEBUG ); $stderr = ''; $obj->debug('hello world'); ok( ! $stderr ) or print "stderr is [$stderr] not empty'\n"; # no explicit debug flag set in object, so should use package var $My::Class::Base::DEBUG = 1; ok( ! $obj->debugging, 'object is not debugging' ); ok( My::Class::Base->debugging, 'class is debugging' ); $stderr = ''; $obj->debug('hello world'); ok( ! $stderr, 'stderr is empty' ); My::Class::Base->debug('hello world'); ok( $stderr eq '[My::Class::Base] hello world' ) or print "stderr is [$stderr] not '[My::Class::Base] hello world'\n"; # now we set an object debug flag which should also change pkg var $obj->debugging(0); ok( ! $obj->debugging, 'object debuggin off' ); ok( $My::Class::Base::DEBUG, 'class debugging on' ); $stderr = ''; $obj->debug('hello world'); ok( ! $stderr ) or print "stderr is [$stderr] not empty\n"; # now that object has debug value defined, it not longer uses pkg var $My::Class::Base::DEBUG = 1; ok( ! $obj->debugging ); $obj->debug('hello world'); ok( ! $stderr ) or print "stderr is [$stderr] not empty\n"; # test debugging works as class method My::Class::Base->debugging(0); ok( ! $My::Class::Base::DEBUG ); My::Class::Base->debugging(1); ok( $My::Class::Base::DEBUG ); }; subtest 'package $DEBUG variable sets default object DEBUG flag' => sub { My::Class::Base->debugging(0); ok( ! $My::Class::Base::DEBUG, 'class debugging is off' ); my $obj1 = My::Class::Base->new( ); ok( $obj1, 'object 1 created' ); ok( ! $obj1->debugging, 'object not debugging' ); $stderr = ''; $obj1->debug('foo'); ok( ! $stderr, 'nothing printed' ); My::Class::Base->debugging(1); ok( $My::Class::Base::DEBUG, 'class debugging is now on' ); my $obj2 = My::Class::Base->new( ); ok( $obj2, 'object 2 created' ); ok( $obj2->debugging, 'object is debugging' ); $stderr = ''; $obj2->debug('foo'); is( $stderr, '[My::Class::Base] foo', 'foo printed' ); }; #------------------------------------------------------------------------ # test package var $DEBUG influences debug flag of new objects #------------------------------------------------------------------------ package Some::Class; use base qw( Class::Base ); our $DEBUG = 0 unless defined $DEBUG; local $" = ', '; sub one { my ($self, @args) = @_; $self->debug("one(@args)\n"); } sub two { my ($self, @args) = @_; $self->debug("two(@args)\n") if $DEBUG; } ; package main; my $a = Some::Class->new(debug => 1); my $b = Some::Class->new(debug => 1); $stderr = ''; $a->one(2); $a->two(3); $b->one(5); $b->two(7); is( $stderr, "[Some::Class] one(2)\n[Some::Class] one(5)\n", 'output 1 matches'); $a->debugging(0); $stderr = ''; $a->one(11); $a->two(13); $b->one(17); $b->two(19); is( $stderr, "[Some::Class] one(17)\n", 'output 2 matches'); Some::Class->debugging(1); $stderr = ''; $a->one(23); $a->two(29); $b->one(31); $b->two(37); is( $stderr, "[Some::Class] one(31)\n[Some::Class] two(37)\n", 'output 3 matches'); #------------------------------------------------------------------------ # test params() method #------------------------------------------------------------------------ package My::Params::Test; use base qw( Class::Base ); sub init { my ($self, $config) = @_; my ($one, $two, $three) = $self->params($config, qw( ONE TWO THREE )) || return; return $self; } package main; $pkg = 'My::Params::Test'; my $obj = $pkg->new(); ok( $obj, 'got an object' ); ok( ! exists $obj->{ ONE }, 'ONE does not exist' ); $obj = $pkg->new( ONE => 2 ); ok( $obj, 'got an object' ); is( $obj->{ ONE }, 2, 'ONE is 2' ); $obj = $pkg->new( one => 3, TWO => 4 ); ok( $obj, 'got an object' ); is( $obj->{ ONE }, 3, 'ONE is 3' ); is( $obj->{ TWO }, 4, 'TWO is 4' ); ok( ! exists $obj->{ THREE }, 'THREE does not exist' ); #------------------------------------------------------------------------ # same passing list of args #------------------------------------------------------------------------ package My::Other::Params::Test; use base qw( Class::Base ); sub init { my ($self, $config) = @_; my ($one, $two, $three) = $self->params($config, [ qw( ONE TWO THREE ) ]) || return; return $self; } package main; $pkg = 'My::Params::Test'; $obj = $pkg->new(); ok( $obj, 'got a list ref object' ); ok( ! exists $obj->{ ONE }, 'ONE does not exist' ); $obj = $pkg->new( ONE => 2 ); is( $obj->{ ONE }, 2, 'ONE is 2' ); $obj = $pkg->new( one => 3, TWO => 4 ); is( $obj->{ ONE }, 3, 'ONE is 3' ); is( $obj->{ TWO }, 4, 'TWO is 4' ); ok( ! exists $obj->{ THREE }, 'THREE does not exist' ); #------------------------------------------------------------------------ # same passing hash of defaults #------------------------------------------------------------------------ package My::Hash::Params::Test; use base qw( Class::Base ); sub init { my ($self, $config) = @_; my ($one, $two, $three) = $self->params($config, { FOO => 'the foo item', BAR => undef, BAZ => \&baz, }) || return; return $self; } sub baz { my ($self, $key, $value) = @_; $value = '' unless defined $value; $self->{ MSG } = "$key set to $value"; $self->{ BAZ } = $value; } package main; $pkg = 'My::Hash::Params::Test'; $obj = $pkg->new(); ok( $obj, 'got a hash ref object' ); is( $obj->{ FOO }, 'the foo item', 'foo default set' ); ok( ! exists $obj->{ BAR }, 'BAR does not exist' ); is( $obj->{ BAZ }, '', 'BAZ is undef' ); is( $obj->{ MSG }, 'BAZ set to ', 'BAZ is undef' ); $obj = $pkg->new( foo => 'hello world', bar => 99, baz => 'bazmatic' ); is( $obj->{ FOO }, 'hello world', 'foo set' ); is( $obj->{ BAR }, '99', 'bar set' ); is( $obj->{ BAZ }, 'bazmatic', 'baz is set' ); is( $obj->{ MSG }, 'BAZ set to bazmatic', 'MSG is set' ); Class-Base-0.09/TODO0000644000175000017500000000051713223464640013374 0ustar yanickyanick* I think things like debug() and debugging() should be part of a Class::Base::Debug mixin, but for now they're in here. * Other mixins might include Class::Base::Factory for providing factory() and create() methods which interface to uhm, Class::Factory, oh, I see Chris Winters has already written that, oh good... hmmm... Class-Base-0.09/dist.ini0000644000175000017500000000046313223464640014350 0ustar yanickyanickname = Class-Base author = Andy Wardley author = Gabor Szabo author = Yanick Champoux license = Perl_5 copyright_holder = Andy Wardley copyright_year = 1996-2012 [@Filter] -bundle=@YANICK -remove=Covenant NextVersion::Semantic.format=%d.%02d Class-Base-0.09/doap.xml0000644000175000017500000000746313223464640014360 0ustar yanickyanick Class-Base useful base class for deriving other modules Andy Wardley Gabor Szabo Yanick Champoux Gabor Szabo Kent Fredric Nick Morrott Yanick Champoux 0.01 2002 0.02 2002 0.03 2002 0.04 2012 0.05 2012 0.06 2014 0.07 2016 0.08 2016 Perl Class-Base-0.09/README0000644000175000017500000004264513223464640013574 0ustar yanickyanickNAME Class::Base - useful base class for deriving other modules SYNOPSIS package My::Funky::Module; use base qw( Class::Base ); # custom initialiser method sub init { my ($self, $config) = @_; # copy various params into $self $self->params($config, qw( FOO BAR BAZ )) || return undef; # to indicate a failure return $self->error('bad constructor!') if $something_bad; # or to indicate general happiness and well-being return $self; } package main; # new() constructor folds args into hash and calls init() my $object = My::Funky::Module->new( foo => 'bar', ... ) || die My::Funky::Module->error(); # error() class/object method to get/set errors $object->error('something has gone wrong'); print $object->error(); # debugging() method (de-)activates the debug() method $object->debugging(1); # debug() prints to STDERR if debugging enabled $object->debug('The ', $animal, ' sat on the ', $place); DESCRIPTION This module implements a simple base class from which other modules can be derived, thereby inheriting a number of useful methods such as "new()", "init()", "params()", "clone()", "error()" and "debug()". For a number of years, I found myself re-writing this module for practically every Perl project of any significant size. Or rather, I would copy the module from the last project and perform a global search and replace to change the names. Each time it got a little more polished and eventually, I decided to Do The Right Thing and release it as a module in it's own right. It doesn't pretend to be an all-encompassing solution for every kind of object creation problem you might encounter. In fact, it only supports blessed hash references that are created using the popular, but by no means universal convention of calling "new()" with a list or reference to a hash array of named parameters. Constructor failure is indicated by returning undef and setting the "$ERROR" package variable in the module's class to contain a relevant message (which you can also fetch by calling "error()" as a class method). e.g. my $object = My::Module->new( file => 'myfile.html', msg => 'Hello World' ) || die $My::Module::ERROR; or: my $object = My::Module->new({ file => 'myfile.html', msg => 'Hello World', }) || die My::Module->error(); The "new()" method handles the conversion of a list of arguments into a hash array and calls the "init()" method to perform any initialisation. In many cases, it is therefore sufficient to define a module like so: package My::Module; use Class::Base; use base qw( Class::Base ); sub init { my ($self, $config) = @_; # copy some config items into $self $self->params($config, qw( FOO BAR )) || return undef; return $self; } # ...plus other application-specific methods 1; Then you can go right ahead and use it like this: use My::Module; my $object = My::Module->new( FOO => 'the foo value', BAR => 'the bar value' ) || die $My::Module::ERROR; Despite its limitations, Class::Base can be a surprisingly useful module to have lying around for those times where you just want to create a regular object based on a blessed hash reference and don't want to worry too much about duplicating the same old code to bless a hash, define configuration values, provide an error reporting mechanism, and so on. Simply derive your module from "Class::Base" and leave it to worry about most of the detail. And don't forget, you can always redefine your own "new()", "error()", or other method, if you don't like the way the Class::Base version works. Subclassing Class::Base This module is what object-oriented afficionados would describe as an "abstract base class". That means that it's not designed to be used as a stand-alone module, rather as something from which you derive your own modules. Like this: package My::Funky::Module use base qw( Class::Base ); You can then use it like this: use My::Funky::Module; my $module = My::Funky::Module->new(); Construction and Initialisation Methods If you want to apply any per-object initialisation, then simply write an "init()" method. This gets called by the "new()" method which passes a reference to a hash reference of configuration options. sub init { my ($self, $config) = @_; ... return $self; } When you create new objects using the "new()" method you can either pass a hash reference or list of named arguments. The "new()" method does the right thing to fold named arguments into a hash reference for passing to the "init()" method. Thus, the following are equivalent: # hash reference my $module = My::Funky::Module->new({ foo => 'bar', wiz => 'waz', }); # list of named arguments (no enclosing '{' ... '}') my $module = My::Funky::Module->new( foo => 'bar', wiz => 'waz' ); Within the "init()" method, you can either handle the configuration yourself: sub init { my ($self, $config) = @_; $self->{ file } = $config->{ file } || return $self->error('no file specified'); return $self; } or you can call the "params()" method to do it for you: sub init { my ($self, $config) = @_; $self->params($config, 'file') || return $self->error('no file specified'); return $self; } Error Handling The "init()" method should return $self to indicate success or undef to indicate a failure. You can use the "error()" method to report an error within the "init()" method. The "error()" method returns undef, so you can use it like this: sub init { my ($self, $config) = @_; # let's make 'foobar' a mandatory argument $self->{ foobar } = $config->{ foobar } || return $self->error("no foobar argument"); return $self; } When you create objects of this class via "new()", you should now check the return value. If undef is returned then the error message can be retrieved by calling "error()" as a class method. my $module = My::Funky::Module->new() || die My::Funky::Module->error(); Alternately, you can inspect the "$ERROR" package variable which will contain the same error message. my $module = My::Funky::Module->new() || die $My::Funky::Module::ERROR; Of course, being a conscientious Perl programmer, you will want to be sure that the "$ERROR" package variable is correctly defined. package My::Funky::Module use base qw( Class::Base ); our $ERROR; You can also call "error()" as an object method. If you pass an argument then it will be used to set the internal error message for the object and return undef. Typically this is used within the module methods to report errors. sub another_method { my $self = shift; ... # set the object error return $self->error('something bad happened'); } If you don't pass an argument then the "error()" method returns the current error value. Typically this is called from outside the object to determine its status. For example: my $object = My::Funky::Module->new() || die My::Funky::Module->error(); $object->another_method() || die $object->error(); Debugging Methods The module implements two methods to assist in writing debugging code: debug() and debugging(). Debugging can be enabled on a per-object or per-class basis, or as a combination of the two. When creating an object, you can set the "DEBUG" flag (or lower case "debug" if you prefer) to enable or disable debugging for that one object. my $object = My::Funky::Module->new( debug => 1 ) || die My::Funky::Module->error(); my $object = My::Funky::Module->new( DEBUG => 1 ) || die My::Funky::Module->error(); If you don't explicitly specify a debugging flag then it assumes the value of the "$DEBUG" package variable in your derived class or 0 if that isn't defined. You can also switch debugging on or off via the "debugging()" method. $object->debugging(0); # debug off $object->debugging(1); # debug on The "debug()" method examines the internal debugging flag (the "_DEBUG" member within the "$self" hash) and if it finds it set to any true value then it prints to STDERR all the arguments passed to it. The output is prefixed by a tag containing the class name of the object in square brackets (but see the "id()" method below for details on how to change that value). For example, calling the method as: $object->debug('foo', 'bar'); prints the following output to STDERR: [My::Funky::Module] foobar When called as class methods, "debug()" and "debugging()" instead use the "$DEBUG" package variable in the derived class as a flag to control debugging. This variable also defines the default "DEBUG" flag for any objects subsequently created via the new() method. package My::Funky::Module use base qw( Class::Base ); our $ERROR; our $DEBUG = 0 unless defined $DEBUG; # some time later, in a module far, far away package main; # debugging off (by default) my $object1 = My::Funky::Module->new(); # turn debugging on for My::Funky::Module objects $My::Funky::Module::DEBUG = 1; # alternate syntax My::Funky::Module->debugging(1); # debugging on (implicitly from $DEBUG package var) my $object2 = My::Funky::Module->new(); # debugging off (explicit override) my $object3 = My::Funky::Module->new(debug => 0); If you call "debugging()" without any arguments then it returns the value of the internal object flag or the package variable accordingly. print "debugging is turned ", $object->debugging() ? 'on' : 'off'; METHODS new() Class constructor method which expects a reference to a hash array of parameters or a list of "name => value" pairs which are automagically folded into a hash reference. The method blesses a hash reference and then calls the "init()" method, passing the reference to the hash array of configuration parameters. Returns a reference to an object on success or undef on error. In the latter case, the "error()" method can be called as a class method, or the "$ERROR" package variable (in the derived class' package) can be inspected to return an appropriate error message. my $object = My::Class->new( foo => 'bar' ) # params list || die $My::Class::$ERROR; # package var or my $object = My::Class->new({ foo => 'bar' }) # params hashref || die My::Class->error; # class method init(\%config) Object initialiser method which is called by the "new()" method, passing a reference to a hash array of configuration parameters. The method may be derived in a subclass to perform any initialisation required. It should return "$self" on success, or "undef" on error, via a call to the "error()" method. package My::Module; use base qw( Class::Base ); sub init { my ($self, $config) = @_; # let's make 'foobar' a mandatory argument $self->{ foobar } = $config->{ foobar } || return $self->error("no foobar argument"); return $self; } params($config, @keys) The "params()" method accept a reference to a hash array as the first argument containing configuration values such as those passed to the "init()" method. The second argument can be a reference to a list of parameter names or a reference to a hash array mapping parameter names to default values. If the second argument is not a reference then all the remaining arguments are taken as parameter names. Thus the method can be called as follows: sub init { my ($self, $config) = @_; # either... $self->params($config, qw( foo bar )); # or... $self->params($config, [ qw( foo bar ) ]); # or... $self->params($config, { foo => 'default foo value', bar => 'default bar value' } ); return $self; } The method looks for values in $config corresponding to the keys specified and copies them, if defined, into $self. Keys can be specified in UPPER CASE and the method will look for either upper or lower case equivalents in the "$config" hash. Thus you can call "params()" from "init()" like so: sub init { my ($self, $config) = @_; $self->params($config, qw( FOO BAR )) return $self; } but use either case for parameters passed to "new()": my $object = My::Module->new( FOO => 'the foo value', BAR => 'the bar value' ) || die My::Module->error(); my $object = My::Module->new( foo => 'the foo value', bar => 'the bar value' ) || die My::Module->error(); Note however that the internal key within "$self" used to store the value will be in the case provided in the call to "params()" (upper case in this example). The method doesn't look for upper case equivalents when they are specified in lower case. When called in list context, the method returns a list of all the values corresponding to the list of keys, some of which may be undefined (allowing you to determine which values were successfully set if you need to). When called in scalar context it returns a reference to the same list. clone() The "clone()" method performs a simple shallow copy of the object hash and creates a new object blessed into the same class. You may want to provide your own "clone()" method to perform a more complex cloning operation. my $clone = $object->clone(); error($msg, ...) General purpose method for getting and setting error messages. When called as a class method, it returns the value of the "$ERROR" package variable (in the derived class' package) if called without any arguments, or sets the same variable when called with one or more arguments. Multiple arguments are concatenated together. # set error My::Module->error('set the error string'); My::Module->error('set ', 'the ', 'error string'); # get error print My::Module->error(); print $My::Module::ERROR; When called as an object method, it operates on the "_ERROR" member of the object, returning it when called without any arguments, or setting it when called with arguments. # set error $object->error('set the error string'); # get error print $object->error(); The method returns "undef" when called with arguments. This allows it to be used within object methods as shown: sub my_method { my $self = shift; # set error and return undef in one return $self->error('bad, bad, error') if $something_bad; } debug($msg, $msg, ...) Prints all arguments to STDERR if the internal "_DEBUG" flag (when called as an object method) or "$DEBUG" package variable (when called as a class method) is set to a true value. Otherwise does nothing. The output is prefixed by a string of the form "[Class::Name]" where the name of the class is that returned by the "id()" method. debugging($flag) Used to get (no arguments) or set ($flag defined) the value of the internal "_DEBUG" flag (when called as an object method) or "$DEBUG" package variable (when called as a class method). id($newid) The "debug()" method calls this method to return an identifier for the object for printing in the debugging message. By default it returns the class name of the object (i.e. "ref $self"), but you can of course subclass the method to return some other value. When called with an argument it uses that value to set its internal "_ID" field which will be returned by subsequent calls to "id()". AUTHOR Andy Wardley VERSION This is version 0.03 of Class::Base. HISTORY This module began life as the Template::Base module distributed as part of the Template Toolkit. Thanks to Brian Moseley and Matt Sergeant for suggesting various enhancments, some of which went into version 0.02. COPYRIGHT Copyright (C) 1996-2002 Andy Wardley. All Rights Reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.