Class-Trait-0.31000755000765000765 011320064415 12656 5ustar00ovidovid000000000000Build.PL000444000765000765 110211320064415 14222 0ustar00ovidovid000000000000Class-Trait-0.31use strict; use warnings; use Module::Build; my $builder = Module::Build->new( module_name => 'Class::Trait', license => 'perl', dist_author => 'Curtis "Ovid" Poe ', dist_version_from => 'lib/Class/Trait.pm', requires => { 'Test::Differences' => 0.47, 'Test::Simple' => 0.62, 'File::Spec' => 0, 'Class::Accessor::Fast' => 0, }, add_to_cleanup => ['Class-Trait-*'], create_makefile_pl => 'traditional', ); $builder->create_build_script(); Changes000444000765000765 711511320064413 14231 0ustar00ovidovid000000000000Class-Trait-0.31Revision history for Perl extension Class::Trait. 0.31 Jan 3, 2010 (bug fixes) - Normalized version numbers. - Fixed lvalue bug which broke the debugger and profiler. [rt#23709] - Fixed 'defined %hash' bug which broke bleadperl. [rt#23709] 0.30 Oct 18, 2009 - Added deprecation notice. No new features or bug fixes are intended. 0.22 Oct 25, 2006 - Fixed bug where does() failed when inherited. Reported by Romano Daniel. - Cleaned up the MANIFEST 0.21 Feb. 15, 2006 - Suppressed "void" warnings for mod_perl in the INIT phase. 0.20 Nov. 26, 2005 - Added ability to apply traits at runtime to instances and classes - Changed 'die' to 'croak' - Renumbered tests. - Made most private subs in Class::Trait begin with an underscore. - Eliminated subtle bug where reusing a trait with excluded methods could fail. It doubtful anyone would ever encounter this, but still ... 0.11 Nov. 19, 2005 - Added tests to ensure that failure messages were correct. - Fixed bug where not all conflicting methods were being recognized. - If only a single method is to be excluded, you may specify the method name without having to wrap it in an array reference. - Clean up debugging code. Only call debug() if needed. - Only use Data::Dumper if debugging. - Eliminated "uninitialized" warning when Class::Trait can't determine the package a method originated it. - Added "BUGS" section to documentation. All known bugs have easy workarounds. 0.10 Nov. 17, 2005 - BUG FIX: Traits only provide methods defined in the trait. Imported subroutines are no longer "provided". - Reformatted - Add Module::Build support 0.07 Nov. 16, 2005 *** API CHANGE *** - "is" is no longer exported. Instead, programmers have the option of renaming the "does" method to something more suitable for their needs. 0.06 Nov. 15, 2005 - Renamed "is" method to "does". This is the same method name used with Perl 6 roles and avoids conflicts with Test::More::is(). - &is is now offically deprecated, it will be removed after a few more releases - Thanks to Curtis "Ovid" Poe for this code change 0.05 Sept. 14, 2005 - fixed a bug in TEquality::isExactly - fixed Class::Trait::Reflection, it was loading Class::Trait in the wrong way - fixed path handling for Class::Trait, now uses File::Spec to create cross platform paths. - fixed the loading of traits with :: in them, this used to fail use Class::Trait qw(My::Trait); it works now. Thanks to Yuval Kogman for finding the issue. - SUPER:: handling now dispatches properly. Thanks to Roman Daniel for the code and tests. 0.04 May 24, 2004 - Added a default Trait Library which for now only contains 3 traits; TEquality, TComparable, TPrintable. See their documentation for more details on them. If these names are given, they are loaded from the trait's library. 0.03 Wed April 28th 2004 - made this workable with mod_perl and reduced dependence on the INIT block. I am not 100% happy with it yet though, so there will be further changes coming. 0.02 Mon April 19th 2004 - Made "is" method search depth first down the Trait tree instead of just checking the top level trait and subtraits. - Spruced up the test suite alot, adding about 121 new tests. - Cleaned up some documentation issues. And updated anything that needed it. 0.01 Sun Mar 7 08:09:00 EST 2004 - first release of Class::Trait 0.01 Makefile.PL000444000765000765 107511320064415 14711 0ustar00ovidovid000000000000Class-Trait-0.31# Note: this file was auto-generated by Module::Build::Compat version 0.35 use ExtUtils::MakeMaker; WriteMakefile ( 'NAME' => 'Class::Trait', 'VERSION_FROM' => 'lib/Class/Trait.pm', 'PREREQ_PM' => { 'Class::Accessor::Fast' => 0, 'File::Spec' => 0, 'Test::Differences' => '0.47', 'Test::Simple' => '0.62' }, 'INSTALLDIRS' => 'site', 'EXE_FILES' => [], 'PL_FILES' => {} ) ; MANIFEST000444000765000765 260311320064413 14064 0ustar00ovidovid000000000000Class-Trait-0.31Build.PL Changes lib/Class/Trait.pm lib/Class/Trait/Base.pm lib/Class/Trait/Config.pm lib/Class/Trait/Lib/TComparable.pm lib/Class/Trait/Lib/TEquality.pm lib/Class/Trait/Lib/TPrintable.pm lib/Class/Trait/Reflection.pm Makefile.PL MANIFEST META.yml Module meta-data (added by MakeMaker) README t/010_class_trait.t t/020_test_imports.t t/030_trait_overload.t t/040_trait_composition.t t/050_Trait_Config_test.t t/060_Trait_SUPER_test.t t/070_Trait_mod_perl_test.t t/080_Trait_SUPER2_test.t t/090_Class_Trait_Lib_tests.t t/100_trait_rename_does.t t/110_trait_performs.t t/120_trait_errors.t t/130_trait_runtime_instance.t t/140_trait_runtime_class.t t/150_inherited_does.t t/pod.t t/pod_coverage.t t/Test/Another/ColonInTheName.pm t/Test/LoadingTraitsWithColonsInThem.pm t/test_lib/BasicTrait.pm t/test_lib/BasicTraitImport.pm t/test_lib/Circle.pm t/test_lib/Employee.pm t/test_lib/Extra/TSpouse.pm t/test_lib/FooExport.pm t/test_lib/Original/TSpouse.pm t/test_lib/Person.pm t/test_lib/PersonWithTitle.pm t/test_lib/Read.pm t/test_lib/RenameDoesToPerforms.pm t/test_lib/SyncRead.pm t/test_lib/TBomb.pm t/test_lib/TCircle.pm t/test_lib/TColor.pm t/test_lib/TCompositeTest.pm t/test_lib/TDisallowed.pm t/test_lib/TGeometry.pm t/test_lib/TImport.pm t/test_lib/TMagnitude.pm t/test_lib/TraitTest.pm t/test_lib/TraitTestBase.pm t/test_lib/TSimple.pm t/test_lib/TSpouse.pm t/test_lib/TSyncRead.pm t/test_lib/Ttitle.pm META.yml000444000765000765 176011320064414 14210 0ustar00ovidovid000000000000Class-Trait-0.31--- name: Class-Trait version: 0.31 author: - 'Curtis "Ovid" Poe ' abstract: Deprecated. Please use Moose::Role. license: perl resources: license: http://dev.perl.org/licenses/ requires: Class::Accessor::Fast: 0 File::Spec: 0 Test::Differences: 0.47 Test::Simple: 0.62 configure_requires: Module::Build: 0.35 provides: Class::Trait: file: lib/Class/Trait.pm version: 0.31 Class::Trait::Base: file: lib/Class/Trait/Base.pm version: 0.31 Class::Trait::Config: file: lib/Class/Trait/Config.pm version: 0.31 Class::Trait::Reflection: file: lib/Class/Trait/Reflection.pm version: 0.31 TComparable: file: lib/Class/Trait/Lib/TComparable.pm version: 0.31 TEquality: file: lib/Class/Trait/Lib/TEquality.pm version: 0.31 TPrintable: file: lib/Class/Trait/Lib/TPrintable.pm version: 0.31 generated_by: Module::Build version 0.35 meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: 1.4 README000444000765000765 72611320064415 13601 0ustar00ovidovid000000000000Class-Trait-0.31Class::Trait ===================== INSTALLATION To install this module type the following: perl Build.PL ./Build ./Build test ./Build install DEPENDENCIES This module requires no other modules and libraries outside of the core modules COPYRIGHT AND LICENCE Copyright (C) 2004, 2005 Infinity Interactive, Inc. http://www.iinteractive.com This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. lib000755000765000765 011320064413 13343 5ustar00ovidovid000000000000Class-Trait-0.31Class000755000765000765 011320064414 14411 5ustar00ovidovid000000000000Class-Trait-0.31/libTrait.pm000444000765000765 16522411320064414 16241 0ustar00ovidovid000000000000Class-Trait-0.31/lib/Classpackage Class::Trait; use strict; use warnings; our $VERSION = '0.31'; use overload (); use File::Spec (); use B qw/svref_2object/; use Scalar::Util qw/blessed/; sub _croak($) { my $message = shift; require Carp; Carp::croak($message); } sub _sub_package { my $package; eval { my $stash = svref_2object(shift)->STASH; if ( $stash && $stash->can('NAME') ) { $package = $stash->NAME; } else { $package = ''; } }; if ($@) { warn "Could not determine calling package: $@"; } return $package; } ## ---------------------------------------------------------------------------- ## Debugging functions ## ---------------------------------------------------------------------------- # make a sub sub DEBUG {0} require Data::Dumper if DEBUG; # this is accessable to the package my $debug_indent = 0; { # this however is not accessable to anyone but the debug function my $debug_line_number = 1; # debuggin' sub debug { return unless DEBUG; # otherwise debug my $formatted_debug_line_number = sprintf( "%03d", $debug_line_number ); print STDERR "debug=($formatted_debug_line_number) ", ( " " x $debug_indent ), @_, "\n"; $debug_line_number++; } } ## ---------------------------------------------------------------------------- # This allows us to rename "does" to something which does not conflict with a # method in the current package. Also, for backwards compatability, one can # specifiy Class::Trait->relation('is'); my $NAME_FOR_DOES = 'does'; sub _name_for_does { $NAME_FOR_DOES; } # XXX OK, admit it. This function is a right mess. I'm embarrassed. my %PACKAGE_DOES; my $DOES = sub { my $proto = shift; my $class = ref($proto) || $proto; my $trait; if ( !$proto->isa('Class::Trait::Config') ) { no strict 'refs'; $trait = ${"${class}::TRAITS"} or do { # if we've gotten to here, then the TRAITS are not defined in the # current package. This implies that we have a subclass # inheriting from a class which uses traits and the does() method # needs to search the inheritance heirarchy. foreach my $parent ( @{"${class}::ISA"} ) { my @result = $parent->$NAME_FOR_DOES(@_) if $parent->can($NAME_FOR_DOES); next unless @result; if (@_) { return $result[0] || (); } return @result; } }; } else { $trait = $proto; } if (@_) { my $trait_name = shift; if ( exists $PACKAGE_DOES{$class}{$trait_name} ) { return 1; } my $does = _recursive_does( $trait, $trait_name ); return $does if $does; # we have runtime traits applied to instances if ( $class =~ /__ANON__/ ) { no strict 'refs'; ($class) = @{"${class}::ISA"}; # ANON traits have single inheritance return $class->$NAME_FOR_DOES($trait_name) if $class->can($NAME_FOR_DOES); } return $does; } else { my %does = map { $_ => 1 } _all_does($trait), keys %{ $PACKAGE_DOES{$class} }; # we have runtime traits applied to instances if ( $class =~ /__ANON__/ ) { no strict 'refs'; ($class) = @{"${class}::ISA"}; # ANON traits have single inheritance if ( $class->can($NAME_FOR_DOES) ) { foreach my $does ( $class->$NAME_FOR_DOES ) { $does{$does} = 1; } } if ( exists $PACKAGE_DOES{$class} ) { foreach my $does ( keys %{ $PACKAGE_DOES{$class} } ) { $does{$does} = 1; } } } return keys %does; } }; # a trait cache, so we can avoid re-processing traits we already have # processed. This is checked by the trait_load function prior to reading the # trait in my %CACHE = (); # load the config class use Class::Trait::Config; # base class for traits use Class::Trait::Base; # save packages that need to be checked for meeting requirements here my %TRAITS_TO_CHECK = (); sub _clear_all_caches { %CACHE = (); %TRAITS_TO_CHECK = (); } # XXX this is merely a testing hook sub _clear_does_cache { %PACKAGE_DOES = (); } # these traits are supplied "for free" my $TRAIT_LIB_ROOT = File::Spec->catfile(qw(Class Trait Lib)); my %TRAIT_LIB = map { $_ => 1 } qw( TEquality TPrintable TComparable ); ## ---------------------------------------------------------------------------- sub import { my $class = shift; # just loading the module does not mean we have any traits to give it, so # we return if there is nothing return unless @_; # but if we have something, then ... my ($package) = caller(); # if we are being asked to make a trait a trait then ... if ( $_[0] eq "debug" ) { no strict 'refs'; no warnings 'redefine'; *{"Class::Trait::DEBUG"} = sub {1}; } elsif ( $_[0] eq "base" ) { no strict 'refs'; # push our base into the front # of the ISA list unshift @{"${package}::ISA"} => 'Class::Trait::Base'; if ( defined( my $name_for_does = $_[1] ) ) { $class->_set_does( $package, $name_for_does ); } } # otherwise we are using traits else { if (DEBUG) { debug "^ compiling/processing traits for $package"; $debug_indent++; } _apply_traits( $package, _compile_traits( $package, @_ ) ); $debug_indent-- if DEBUG; } } # XXX we kick the anonymous counter every time we apply a trait to an instance # in order to guarantee that no two anonymous classes can ever share the same # name. my $anon_counter = 1; sub apply { my ( $class, $proto, @traits ) = @_; # failing to clear the caches means that trait information from one # instance can bleed to another when resolving conflicts _clear_all_caches(); my $target_class = blessed $proto ? _setup_anonymous_class( $proto, @traits ) : $proto; eval { _apply_traits( $target_class, _compile_traits( $target_class, @traits ), 1 ); }; _croak $@ if $@; if ( blessed $proto) { # XXX bless the object after attempting to apply traits. Otherwise, # someone at the top level could be applying a trait in an eval and # getting the object blessed into the new class even though the trait # application failed. bless $proto, $target_class; } $class->initialize; return $class; } sub _setup_anonymous_class { my ( $instance, @traits ) = @_; my $name = join( '', grep { !ref } @traits ) . "_" . $anon_counter++; my $package = ref $instance; if ( $package =~ /^(.*)?::__ANON__::/ ) { $package = $1; # trim old anonymous info } my $anon_class = "${package}::__ANON__::$name"; { no strict 'refs'; @{"${anon_class}::ISA"} = ref $instance; } return $anon_class; } sub _apply_traits { my ( $package, $composite_trait_config, $override_methods ) = @_; if (DEBUG) { debug "> proccessing traits for $package"; $debug_indent++; } if ( $package->isa('Class::Trait::Base') ) { _apply_traits_to_trait( $package, $composite_trait_config ); } else { # we now apply the traits in the BEGIN phase this allows the modules # to be used under mod_perl, however see the documentation for some # important caveats _apply_traits_to_package( $package, $composite_trait_config, $override_methods ); # we still do try to verify the traits in the INIT phase debug "~ verification of traits for $package scheduled for INIT phase" if DEBUG; $TRAITS_TO_CHECK{$package} = $composite_trait_config; } if (DEBUG) { $debug_indent--; debug "< finished proccessing traits for $package"; } } NOWARN: { no warnings 'void'; # XXX keep mod_perl happy # INIT now just runs initialize INIT { initialize() if keys %TRAITS_TO_CHECK; } } # initialize checks that all the traits requirements have been fufilled sub initialize { if (DEBUG) { debug "> verifiying traits in packages"; $debug_indent++; } my ( $package, $trait ); while ( ( $package, $trait ) = each %TRAITS_TO_CHECK ) { _check_traits_in_package( $package, $trait ); } if (DEBUG) { $debug_indent--; debug "> finished verifiying traits in packages"; } } sub _check_traits_in_package { my ( $package, $trait ) = @_; if (DEBUG) { debug "? verifying $package has no conflicts with $trait->{name}"; $debug_indent++; } my @conflicting_methods; while ( my ( $method, $conflict ) = each %{ $trait->conflicts } ) { if ($conflict) { push @conflicting_methods, $method; } } if (@conflicting_methods) { @conflicting_methods = sort @conflicting_methods; _croak "Package $package has conflicting methods (@conflicting_methods)"; } $debug_indent-- if DEBUG; if (DEBUG) { debug "? verifying $package fufills the requirements for $trait->{name}"; $debug_indent++; } foreach my $requirement ( keys %{ $trait->requirements } ) { # if the requirement is an operator then we need to put the paren in # front, as that is how overload.pm does it, this will tell us if the # operator has been overloaded or not $requirement = "($requirement" unless is_method_label($requirement); # now check if the package fufills the requirement or not, and croak if # it fails unless ( $package->can($requirement) ) { _croak "Requirement ($requirement) for $trait->{name} not in $package"; } # if it doesn't fail we can go on to the next debug "+ requirement ($requirement) for $trait->{name} fufilled in $package" if DEBUG; } $debug_indent-- if DEBUG; } ## ---------------------------------------------------------------------------- ## trait-to-package application ## ---------------------------------------------------------------------------- sub _apply_traits_to_package { my ( $package, $trait, $override_methods ) = @_; if (DEBUG) { debug "@ applying trait ($trait->{name}) to package ($package)"; $debug_indent++; } _add_trait_methods( $package, $trait, $override_methods ); _add_trait_overloads( $package, $trait, $override_methods ); if (DEBUG) { $debug_indent--; debug "^ storing reference to traits in $package"; } # now storing the trait in the package so that it can be accessable # through reflection. no strict 'refs'; *{"${package}::TRAITS"} = \$trait; __PACKAGE__->_set_does($package); } sub rename_does { shift; # Class::Trait; my ($package) = caller(); __PACKAGE__->_set_does( $package, @_ ); } sub _set_does { my ( $class, $package ) = splice @_, 0, 2; if (@_) { my $name_for_does = shift; if ( !is_method_label($name_for_does) ) { _croak "Illegal name for trait relation method ($name_for_does)"; } $NAME_FOR_DOES = $name_for_does; } no strict 'refs'; no warnings 'redefine'; *{"${package}::$NAME_FOR_DOES"} = $DOES; return $package; } sub _all_does { my $trait = shift; my %trait_does; foreach my $sub_trait ( @{ $trait->sub_traits } ) { $trait_does{$sub_trait} = 1; foreach my $sub_sub_trait ( _all_does( $CACHE{$sub_trait} ) ) { $trait_does{$sub_sub_trait} = 1; } } return keys %trait_does; } sub _recursive_does { my ( $trait, $trait_name ) = @_; return 1 if ( $trait->name eq $trait_name ); foreach my $sub_trait_name ( @{ $trait->sub_traits } ) { # if its on the second level, then we are here return 1 if ( $sub_trait_name eq $trait_name ); # if not, then we need to descend lower return 1 if ( _recursive_does( $CACHE{$sub_trait_name}, $trait_name ) ); } return 0; } # ----------------------------------------------- # private methods used by trait application # ----------------------------------------------- sub _add_trait_methods { my ( $package, $trait, $override_methods ) = @_; if (DEBUG) { debug "> adding trait ($trait->{name}) methods into $package"; $debug_indent++; } my ( $method_label, $method ); while ( ( $method_label, $method ) = each %{ $trait->methods } ) { # NOTE: we allow this routine to check our package for an implemented # method since it is possible that some other package implemented it # before traits did. It is however unlikely. We know too that all # methods will be installed, and that the local implementations will # overwrite these. no strict 'refs'; if ( !defined &{"${package}::$method_label"} || $override_methods ) { # we add it .... debug "+ adding method ($method_label) into $package" if DEBUG; # suppress redefined warnings because traits applied to classes at # runtime are treated as "mixins" no warnings 'redefine'; eval qq{ package $package; sub $method_label { $method(\@_) } }; } else { # otherwise we let the local class's version override the trait version debug "~ $package locally implements method ($method_label)" if DEBUG; } } $debug_indent-- if DEBUG; } sub _add_trait_overloads { my ( $package, $trait, $override_operators ) = @_; if (DEBUG) { debug "> adding trait ($trait->{name}) overloads into $package"; $debug_indent++; } # make sure we don't overwrite any overloads so we must first check to see # if they are defined in the local class and build a temporary set of # overloads to apply. my %overloads = ( fallback => 1 ); my ( $operator, $method_label ); while ( ( $operator, $method_label ) = each %{ $trait->overloads } ) { # NOTE: we allow this routine to check our package for an implemented # operator since it is possible that "overload" was called before the # trait is if ( !defined &{"${package}::($operator"} || $override_operators ) { debug "+ adding operator ($operator) into $package" if DEBUG; $overloads{$operator} = $method_label; } else { debug "~ $package locally implements operator ($operator)" if DEBUG; } } $debug_indent-- if DEBUG; # now add the temporary set of overloads we build overload::OVERLOAD( $package, %overloads ); } ## ---------------------------------------------------------------------------- ## trait-to-trait application ## ---------------------------------------------------------------------------- sub _apply_traits_to_trait { my ( $package, $trait ) = @_; debug "^ storing sub-traits ($trait->{name}) into trait $package" if DEBUG; no strict 'refs'; *{"${package}::TRAITS"} = $trait; } ## ---------------------------------------------------------------------------- ## trait compiling ## ---------------------------------------------------------------------------- # takes a trait declaration and compiles it into a trait configuration we can # use to apply to a particular package # NOTE: this function utilizes functions from the section labled "trait # operations", which can be found at line no. 505 sub _compile_traits { my ( $package, @trait_declarations ) = @_; if (DEBUG) { debug "> compiling traits for $package"; $debug_indent++; } # now we can process our traits my @traits = (); # loop through the declarations while ( defined( my $trait_name = shift @trait_declarations ) ) { $PACKAGE_DOES{$package}{$trait_name} = 1; # get the name if (DEBUG) { debug "+ found trait ($trait_name)"; $debug_indent++; } # and load the trait my $trait_config = _load_trait($trait_name); # then if the next element is a hash ref meaning there are changes to # be made to the trait (exclusion or aliasing), then process that # accordingly if ( ref( $trait_declarations[0] ) eq "HASH" ) { if (DEBUG) { debug "+ found trait declarations for $trait_name in $package"; $debug_indent++; } # get the changes my $trait_changes = shift @trait_declarations; # check for aliases first # NOTE: we need to do this before we check for excludes to allow # for a method to be aliased to a new name, then the old name # excluded to avoid a conflict. if ( exists ${$trait_changes}{alias} ) { if (DEBUG) { debug "> found alias declaration"; $debug_indent++; } _alias_trait_methods( $trait_config, %{ $trait_changes->{alias} } ); $debug_indent-- if DEBUG; } # now check for exludes if ( defined( my $excludes = ${$trait_changes}{exclude} ) ) { if (DEBUG) { debug "> found exclude declaration"; $debug_indent++; } $excludes = [$excludes] unless 'ARRAY' eq ref $excludes; _exclude_trait_methods( $trait_config, $excludes ); $debug_indent-- if DEBUG; } $debug_indent-- if DEBUG; debug "< finished processing trait declarations for $trait_name in $package" if DEBUG; } # our trait is all ready now, so we can then push it onto the list push @traits => $trait_config; $debug_indent-- if DEBUG; } # finally sum them all together into one config (minus any overriding # trait) my $composite_trait_config = _sum_traits(@traits); if (DEBUG) { $debug_indent--; debug "< finished compling traits for $package"; } # now our composite trait is complete return $composite_trait_config; } ## ---------------------------------------------------------------------------- ## trait loader ## ---------------------------------------------------------------------------- sub _load_trait { my ($trait) = @_; # check first to see if we already # have the trait in our cache if ( exists $CACHE{$trait} ) { debug "~ found trait ($trait) in cache" if DEBUG; # return a copy out of our cache return __PACKAGE__->fetch_trait_from_cache($trait); } if (DEBUG) { debug "> loading trait ($trait)"; $debug_indent++; debug "+ requiring ${trait}.pm"; $debug_indent++; } # load the trait ... if ( exists $TRAIT_LIB{$trait} ) { debug "! ${trait} is in our trait lib, ... loading from lib" if DEBUG; eval { require File::Spec->catfile( $TRAIT_LIB_ROOT, "${trait}.pm" ); }; } else { eval "require ${trait}"; } $debug_indent-- if DEBUG; if ($@) { _croak "Trait ($trait) could not be found : $@"; } # otherwise ... # check to make sure it is the proper type $trait->isa('Class::Trait::Base') || _croak "$trait is not a proper trait (inherits from Class::Trait::Base)"; # initialize our trait configuration my $trait_config = Class::Trait::Config->new(); $trait_config->name($trait); _get_trait_requirements($trait_config); _get_trait_methods($trait_config); _get_trait_overloads($trait_config); no strict 'refs'; # if this trait has sub-traits, we need to process them. no warnings 'once'; if ( $trait->isa('Class::Trait::Base') && keys %{"${trait}::TRAITS"} ) { if (DEBUG) { debug "! found sub-traits in trait ($trait)"; $debug_indent++; } $trait_config = _override_trait( \%{"${trait}::TRAITS"}, $trait_config ); if (DEBUG) { $debug_indent--; debug "< dumping trait ($trait) with subtraits (" . ( join ", " => @{ $trait_config->sub_traits } ) . ") : " . Data::Dumper::Dumper($trait_config); } } # put the trait into the cache to avoid having to be processed again _store_trait_in_cache( $trait, $trait_config ); { # traits should be able to tell us which other traits they do no strict 'refs'; no warnings 'redefine'; *{"Class::Trait::Config::$NAME_FOR_DOES"} = $DOES; } if (DEBUG) { $debug_indent--; debug "< finished loading trait ($trait)"; } # then return the fresh config return $trait_config; } # ----------------------------------------------- # private methods used by trait loader # ----------------------------------------------- sub _override_trait { my ( $trait, $overriding_trait ) = @_; # create a new trait config to represent the combined traits my $trait_config = Class::Trait::Config->new(); $trait_config->name($overriding_trait->name); $trait_config->sub_traits([ # if we have a composite trait we dont want to include the name here # as it is actually defined better in the sub_traits field, but if we # don't have a composite, then we want to include the trait name ( ( COMPOSITE() eq $trait->name ) ? () : $trait->name ), @{ $trait->sub_traits } ]); # let the overriding trait override the methods in the regular trait $trait_config->methods( { %{ $trait->methods }, %{ $overriding_trait->methods } } ); # the same for overloads $trait_config->overloads( { %{ $trait->overloads }, %{ $overriding_trait->overloads } } ); # now combine the requirements as well $trait_config->requirements( { %{ $trait->requirements }, %{ $overriding_trait->requirements } } ); if (DEBUG) { debug "? checking for requirement fufillment"; $debug_indent++; } # but we need to check them foreach my $requirement ( keys %{ $trait_config->requirements } ) { if ( is_method_label($requirement) ) { if ( exists ${ $trait_config->methods }{$requirement} ) { debug "+ method requirement ($requirement) is fufilled in overriding trait" if DEBUG; delete ${ $trait_config->requirements }{$requirement}; next; } } else { if ( exists ${ $trait_config->overloads }{$requirement} ) { debug "+ overload requirement ($requirement) is fufilled in overriding trait" if DEBUG; delete ${ $trait_config->requirements }{$requirement}; next; } } debug "* requirement ($requirement) not fufilled in overriding trait" if DEBUG; } if (DEBUG) { $debug_indent--; debug "? checking for conflict resultion"; $debug_indent++; } # now deal with conflicts foreach my $conflict ( keys %{ $trait->conflicts } ) { if ( is_method_label($conflict) ) { if ( exists ${ $trait_config->methods }{$conflict} ) { debug "+ method conflict ($conflict) is resolved in overriding trait" if DEBUG; delete ${ $trait_config->requirements }{$conflict}; next; } } else { if ( exists ${ $trait_config->overloads }{$conflict} ) { debug "+ overload conflict ($conflict) is resolved in overriding trait" if DEBUG; delete ${ $trait_config->requirements }{$conflict}; next; } } debug "* conflict ($conflict) not resolved in overriding trait" if DEBUG; $trait_config->conflicts->{$conflict}++; } $debug_indent-- if DEBUG; return $trait_config; } sub _get_trait_requirements { my ($trait_config) = @_; # this function messes with symbol tables and symbol refs, so turn strict # off in its context no strict 'refs'; ( defined $trait_config->name ) || _croak "Trait must be loaded first before information can be gathered"; my $trait = $trait_config->name; debug "< getting requirements for ${trait}" if DEBUG; # get any requirements in the trait and turn it into a hash so we can # track stuff easier $trait_config->requirements({ map { $_ => 1 } @{"${trait}::REQUIRES"} }) if defined @{"${trait}::"}{REQUIRES}; } sub _get_trait_methods { my ($trait_config) = @_; ( defined $trait_config->name ) || _croak "Trait must be loaded first before information can be gathered"; my $trait = $trait_config->name; debug "< getting methods for ${trait}" if DEBUG; # this function messes with symbol tables and symbol refs, so turn strict # off in its context no strict 'refs'; my %implementation_for; foreach ( keys %{"${trait}::"} ) { my $method = "${trait}::$_"; next unless defined &$method; # make sure we're not grabbing sub imported into the trait next unless _sub_package( \&$method ) eq $trait; if (/(DESTROY|AUTOLOAD)/) { _croak "Trait $trait attempted to implement disallowed method $1"; } $implementation_for{$_} = $method; } $trait_config->methods(\%implementation_for); } sub _get_trait_overloads { my ($trait_config) = @_; # this function messes with symbol tables and symbol refs, so turn strict # off in its context no strict 'refs'; ( defined $trait_config->name ) || _croak "Trait must be loaded first before information can be gathered"; my $trait = $trait_config->name; debug "< getting overloads for ${trait}" if DEBUG; # get the overload parameter hash no warnings 'once'; $trait_config->overloads({ %{"${trait}::OVERLOADS"} }) if keys %{"${trait}::OVERLOADS"}; } ## ---------------------------------------------------------------------------- ## trait cache operations ## ---------------------------------------------------------------------------- # NOTE: the traits are stored as a copy and then fetched as a copy. This is # because we alter our version when we apply declarations (excludes, aliases), # and so we need to make sure our cache stays clean. sub _store_trait_in_cache { my ( $trait_name, $trait_config ) = @_; debug "^ storing ($trait_name) in cache" if DEBUG; $CACHE{$trait_name} = $trait_config->clone(); } sub fetch_trait_from_cache { my ( $class, $trait_name ) = @_; debug "< fetching ($trait_name) from cache" if DEBUG; return $CACHE{$trait_name}->clone(); } ## ---------------------------------------------------------------------------- ## trait operations ## ---------------------------------------------------------------------------- # ----------------------------------------------- # exclusion # ----------------------------------------------- sub _exclude_trait_methods { my ( $trait_config, $exclusions ) = @_; if (DEBUG) { debug "- excluding methods for trait ($trait_config->{name})"; $debug_indent++; } foreach my $exclusion (@$exclusions) { # check we have the method being excluded ( exists ${ $trait_config->methods }{$exclusion} ) # otherwise we throw an exception here || _croak "Attempt to exclude method ($exclusion) that is not in trait ($trait_config->{name})"; debug "- excluding method ($exclusion)" if DEBUG; # if we do have it, so lets exclude it delete ${ $trait_config->methods }{$exclusion}; # and be sure to add it to the list of requirements # unless its already there $trait_config->requirements->{$exclusion}++; } $debug_indent-- if DEBUG; } # ----------------------------------------------- # aliasing # ----------------------------------------------- sub _alias_trait_methods { my ( $trait_config, %aliases ) = @_; debug "=> aliasing methods for trait ($trait_config->{name})" if DEBUG; # Now when aliasing methods for a trait, we need to be sure to move any # operator overloads that are bound to the old method to use the new # method this helps us assure that the intentions of trait is fufilled. So # to facilitate this, we reverse the normal overload hash (operator => # method) to be keyed by method (method => operator), this way we can # access it easier. my %overloads_by_method = reverse %{ $trait_config->overloads }; # no process the aliases $debug_indent++ if DEBUG; foreach my $old_name ( keys %aliases ) { # check we have the method being aliases exists ${ $trait_config->methods }{$old_name} # otherwise we throw an exception here || _croak "Attempt to alias method ($old_name) that is not in trait ($trait_config->{name})"; debug "=> aliasing method ($old_name) to ($aliases{$old_name})" if DEBUG; # if we do have it, so lets alias it $trait_config->methods->{ $aliases{$old_name} } = $trait_config->methods->{$old_name}; # if we find the old method in the overloads, # then we change it to the new one here $trait_config->overloads->{ $overloads_by_method{$old_name} } = $aliases{new_name} if exists $overloads_by_method{$old_name}; } $debug_indent-- if DEBUG; } # ----------------------------------------------- # summation # ----------------------------------------------- # a constant to represent the name of a composite trait, a composite trait's # name is best described as the concatenation of all the names of its # subtraits, but rather than duplicate that information in the name field and # the sub-traits field, we assign a COMPOSITE constant as a placeholder/flag use constant COMPOSITE => "COMPOSITE"; sub _sum_traits { my (@traits) = @_; if ( scalar @traits == 1 ) { # if we have only one trait, it doesn't make sense to sum it since # there is nothing to sum it against debug "< only one trait, no need to sum" if DEBUG; return $traits[0]; } debug "> summing traits (" . ( join ", " => map { $_->{name} } @traits ) . ")" if DEBUG; # initialize our trait configuration my $trait_config = Class::Trait::Config->new(); # we are making a composite trait, so lets call it as such $trait_config->name(COMPOSITE); $debug_indent++ if DEBUG; # and process our traits foreach my $trait (@traits) { push @{ $trait_config->sub_traits } => $trait->name; if (DEBUG) { debug "+ adding trait ($trait->{name}) to composite trait"; $debug_indent++; } # first lets check the methods _fold_in_methods( $trait, $trait_config ); # then check the overloads _fold_in_overloads( $trait, $trait_config ); $debug_indent-- if DEBUG; } $debug_indent-- if DEBUG; # now that we have added all our methods we can check to see if any of our # requirements have been fufilled during that time if (DEBUG) { debug "? checking requirements for sum-ed traits ($trait_config->{name})"; $debug_indent++; } foreach my $trait (@traits) { _check_requirements( $trait, $trait_config ); } $debug_indent-- if DEBUG; # now we have cleared up any requirements and combined all our methods, we # can return the config debug "< traits summed successfully" if DEBUG; return $trait_config; } # ----------------------------------------------- # private methods used by summation # ----------------------------------------------- sub _fold_in_methods { my ( $trait, $trait_config ) = @_; if (DEBUG) { debug "> folding in methods for trait ($trait->{name})"; $debug_indent++; } foreach my $method_label ( keys %{ $trait->methods } ) { if ( exists ${ $trait_config->conflicts }{$method_label} ) { debug "* method ($method_label) is already in conflict" if DEBUG; # move to the next method as we cannot add this one next; } # if the method label already exists in our combined config, then ... if ( exists ${ $trait_config->methods }{$method_label} ) { # check to make sure it is not the same method possibly from a # shared base/sub-trait unless ( $trait_config->methods->{$method_label} eq $trait->methods->{$method_label} ) { # this is a conflict, we need to add the method label onto the # requirements and we need to label that a method is in # conflict. debug "* method ($method_label) is in conflict, added to the requirements" if DEBUG; # method is in conflict... $trait_config->conflicts->{$method_label}++; # so remove any copies ... delete ${ $trait_config->methods }{$method_label}; # and it is considered to be a requirement # for the implementing class $trait_config->requirements->{$method_label}++; } else { debug "~ method ($method_label) is a duplicate, no action was taken" if DEBUG; } } else { debug "+ method ($method_label) added successfully" if DEBUG; # move it $trait_config->methods->{$method_label} = $trait->methods->{$method_label}; } } $debug_indent-- if DEBUG; } sub _fold_in_overloads { my ( $trait, $trait_config ) = @_; if (DEBUG) { debug "> folding in overloads for trait ($trait->{name})"; $debug_indent++; } foreach my $overload ( keys %{ $trait->overloads } ) { if ( exists ${ $trait_config->conflicts }{$overload} ) { debug "* overload ($overload) is already in conflict" if DEBUG; # move to the next overload as we cannot add this one next; } # if we already have it then if ( exists ${ $trait_config->overloads }{$overload} ) { # before we get hasty, lets check out if the method called for # this overload is also in conflict (which if it isn't likely # means that they were the same method) (see method equality # function) my $overload_method = ${ $trait_config->overloads }{$overload}; unless ( ${ $trait_config->conflicts }{$overload_method} ) { debug "~ operator ($overload) is a duplicate, no action was taken" if DEBUG; next; } debug "* operator ($overload) in conflict, added to requirements" if DEBUG; # note the conflict and ... $trait_config->conflicts->{$overload}++; # get rid of it (conflicts results in exclusions) delete ${ $trait_config->overloads }{$overload}; # since the overload is now excluded, then it then # becomes a requirement for the implementing package $trait_config->requirements->{"${overload}"}++; } else { debug "+ operator ($overload) added successfully" if DEBUG; # otherwise add it to the list of methods $trait_config->overloads->{$overload} = $trait->overloads->{$overload}; } } $debug_indent-- if DEBUG; } sub _check_requirements { my ( $trait, $trait_config ) = @_; # now check the requirements debug "? checking for trait ($trait->{name})" if DEBUG; foreach my $requirement ( keys %{ $trait->requirements } ) { # if the method does not exist in # our new combined method group unless ( exists ${ $trait_config->methods }{$requirement} ) { if (DEBUG) { $debug_indent++; debug "* requirement ($requirement) not fufilled"; $debug_indent--; } # make it a reuiqement for the package $trait_config->requirements->{$requirement}++; } } } ## ---------------------------------------------------------------------------- ## utility methods ## ---------------------------------------------------------------------------- # short quick predicate functions sub is_method_label { $_[0] =~ /[[:alpha:]][[:word:]]+/ } 1; __END__ =head1 NAME Class::Trait - Deprecated. Please use Moose::Role. =head1 SYNOPSIS # to turn on debugging (do this before # any other traits are loaded) use Class::Trait 'debug'; # nothing happens, but the module is loaded use Class::Trait; # loads these two traits and flatten them # into the current package use Class::Trait qw(TPrintable TComparable); # loading a trait and performing some # trait operations (alias, exclude) first use Class::Trait ( 'TPrintable' => { alias => { "stringValue" => "strVal" }, exclude => "stringValue", }, ); # loading two traits and performing # a trait operation (exclude) on one # module to avoid method conflicts use Class::Trait 'TComparable' => { # exclude the basic equality method # from TComparable and use the ones # in TEquality instead. exclude => [ "notEqualTo", "equalTo" ] }, 'TEquality' # <- use equalTo and notEqualTo from here ); # when building a trait, you need it # to inherit from the trait meta/base-class # so do this ... use Class::Trait 'base'; =head1 DESCRIPTION This document attempts to explain Traits in terms of Perl. =head2 Trait composition A Trait can be defined as a package containing: =over 4 =item * A set of methods =item * A hash of overloaded operators mapped to the method labels =item * An array of required method labels =back Here is an example of the syntax for a very basic trait: package TPrintable; use Class::Trait 'base'; our @REQUIRES = qw(toString); our %OVERLOADS = ('""' => toString); sub stringValue { my ($self) = @_; require overload; return overload::StrVal($self); } 1; The above example requires the user of the trait to implement a C method, which the overloaded C<""> operator then utilizes. The trait also provides a C method to the consuming class. =head2 Trait usage When a class uses a Trait: =over 4 =item * Requirements All requirements of the traits (or composite trait) must be meet either by the class itself or by one of its base classes. =item * Flattening All the non-conflicting trait (or composite trait) methods are flattened into the class, meaning an entry is created directly in the class's symbol table and aliased to the original trait method. Only methods defined in the trait are used. Subroutines imported into the trait are not used. =item * Conflicts If a method label in a class conflicts with a method label in the trait (or composite trait), the class method is chosen and the trait method is discarded. This only applies to methods defined directly in the class's symbol table, methods inherited from a base class are overridden by the trait method. =back Here is a simple example of the usage of the above trait in a class. package MyClass; use Class::Trait ( 'TPrintable' => { alias => { "strVal" => "stringValue" } exclude => "stringValue", } ); sub stringValue { ... } The above example would use the C trait, aliasing C to the method label C, and then excluding C. This is done to avoid a conflict with C method implemented in the class that uses the trait. =head2 Trait operations When using a trait, the class can make changes to the structure of a trait through the following methods. =over 4 =item * Exclusion An array of method labels to exclude from trait. If only a single method needs to be excluded, you may provide the method name without an array. =item * Alias A hash of old method labels to new method labels. =item * Summation A number of traits can be combined into one. =back =head3 Exclusion This excludes a method from inclusion in the class which is using the trait. It does however cause the method to be added to the traits required methods. This is done because it is possible that other methods within the trait rely on the excluded method, and therefore it must be implemented somewhere in order for the other method to work. =head3 Aliasing Aliasing is not renaming or redefining, it does not remove the old method, but instead just introduces another label for that method. The old method label can be overridden or excluded without affecting the new method label. One special note is that aliasing does move any entry in the overloaded operators to use the new method name, rather than the old method name. This is done since many times aliasing is used in conjunction with exclusion to pre-resolve conflicts. This avoids the orphaning of the operator. =head3 Summation When two or more traits are used by a class (or another trait), the traits are first compiled into a composite trait. The resulting composite trait is: =over 4 =item * Methods A union of all non-conflicting methods of all traits. =item * Operators A union of all non-conflicting operators of all traits. =item * Requirements A union of all unsatisfied requirements of all traits. =back =head4 Method conflicts Method equality if determined by two conditions, the first being method label string equality, the second being the hex address of the code reference (found by stringifying the subroutine reference). If a method in one of the traits is deemed to be in conflict with a method in another trait, the result is the exclusion of that method from the composite trait. The method label is then added to the requirements array for the composite trait. Method conflict can be avoided by using exclusion or a combination of aliasing and exclusion. =head4 Operator conflicts Operator conflicts also result in the exclusion of the operator from the composite trait and the operator then becomes a requirement. =head4 Requirement satisfaction One trait may satisfy the requirements of another trait when they are combined into a composite trait. This results in the removal of the requirement from the requirements array in the composite trait. =head1 RUNTIME TRAIT APPLICATION As of C version 0.20, you can now apply traits at runtime to both classes and instances by using the C method. Applying a trait at runtime is similar to using the trait as a mixin because existing methods will be overwritten. The syntax is: Class::Trait->apply($class_or_instance, @list_of_traits); =head2 Classes Applying a trait at runtime to a class: if ($secure) { Class::Trait->apply($class_name, 'TSecureConnection'); } else { warn "Using insecure connections"; Class::Trait->apply($class_name, 'TInsecureConnection'); } Now all instances of C<$class_name> will have the methods provided by the trait applied. If the trait applied at runtime provides methods already defined in C<$class_name>, the C<$class_name> methods will be silently redefined with the trait's methods. =head2 Instances Applying a trait at runtime to an instance: if ($secure) { Class::Trait->apply($instance, 'TSecureConnection'); } else { warn "Using insecure connections"; Class::Trait->apply($instance, 'TInsecureConnection'); } When applying a trait (or set of traits) to an instance of a class, B that instance gets the new methods. If you want numerous instances to receive the new methods, either apply the trait to all instances or consider applying it to the class. Note that the instance is blessed into a new, anonymous class and it's this class which contains the new methods. =head1 WHEN TO USE TRAITS For a relatively simple class heirarchy you may need traits. There are, however, several key indicators that traits may be beneficial for you. =over 4 =item * Duplicated behavior Whenever you've duplicated behavior across unrelated classes. =item * Multiple inheritance Any time you might think about MI and it's only for code reuse (in other words, the subclass is not a more specific type of a super class) =item * Interfaces Any time you might want a Java-style interface but you also want an implementation to go with that. =item * Mixins Any time you might want to use mixins (have you ever considered exporting methods?) =back =head1 EXPORTS =over 4 =item * B<$TRAITS> While not really exported, Class::Trait leaves the actual Class::Trait::Config object applied to the package stored as scalar in the package variable at C<$TRAITS>. =item * B Class::Trait will export this method into any object which uses traits. By calling this method you can query the kind of traits the object has implemented. The method works much like the perl C method in that it performs a depth-first search of the traits hierarchy and returns true (1) if the object implements the trait, and false (0) otherwise. $my_object_with_traits->does('TPrintable'); Calling C without arguments will return all traits an ojbect does. =item * B Class::Trait used to export this method to any object which uses traits, but it was found to conflict with Test::More::is. The recommended way is to use C. To use C instead of C, one trait must use the following syntax for inheritance: use Class::Trait qw/base is/; Instead of: use Class::Trait 'base'; It is recommended that all traits use this syntax if necessary as the mysterious "action at a distance" of renaming this method can be confusing. As an alternative, you can also simply use the following in any code which uses traits: BEGIN { require Class::Trait; Class::Trait->rename_does('is'); } This is generally not recommended in test suites as Test::More::is() conflicts with this method. =back =head1 METHODS =over 4 =item B Class::Trait uses the INIT phase of the perl compiler, which will not run under mod_perl or if a package is loaded at runtime with C. In order to insure that all traits a properly verified, this method must be called. However, you may still use Class::Trait without doing this, for more details see the L section. =item B Note: You probably do not want to use this method. Class::Trait uses C to determine if a class can "do" a particular trait. However, your package may already have a C method defined or you may be migrating from an older version of L which uses C to perform this function. To rename C to something more suitable, you can use this at the top of your code: BEGIN { require Class::Trait; # we do not want to call import() Class::Trait->rename_does($some_other_method_name); } use Class::Trait 'some_trait'; If you wish to shield your users from seeing this, you can declare any trait with: use Class::Trait qw/base performs/; # 'performs' can be any valid method name You only need to do that in one trait and all traits will pick up the new method name. =back =head1 TRAIT LIBRARY I have moved some of the traits in the test suite to be used outside of this, and put them in what I am calling the trait library. This trait library will hopefully become a rich set of base level traits to use when composing your own traits. Currently there are the following pre-defined traits. =over 4 =item * TPrintable =item * TEquality =item * TComparable =back These can be loaded as normal traits would be loaded, Class::Trait will know where to find them. For more information about them, see their own documenation. =head1 DEBUGGING Class::Trait is really an experimental module. It is not ready yet to be used seriously in production systems. That said, about half of the code in this module is dedicated to formatting and printing out debug statements to STDERR when the debug flag is turned on. use Class::Trait 'debug'; The debug statements prints out pretty much every action taken during the traits compilation process and on occasion dump out B output of trait structures. If you are at all interested in traits or in this module, I recommend doing this, it will give you lots of insight as to what is going on behind the scences. =head1 CAVEAT This module uses the INIT phase of the perl compiler to do a final check of the of the traits. Mostly it checkes that the traits requirements are fufilled and that your class is safe to use. This presents a problem in two specific cases. =over 5 =item B mod_perl loads B code through some form of eval. It does this I the normal compilation phases are complete. This means we cannot run INIT. =item B If you load code with C or C the result is the same as with mod_perl. It is post-compilation, and the INIT phase cannot be run. =back However, this does not mean you cannot use Class::Trait in these two scenarios. Class::Trait will just not check its requirements, these routines will simply throw an error if called. The best way to avoid this is to call the class method C, after you have loaded all your classes which utilize traits, or after you specifically load a class with traits at runtime. Class::Trait->initialize(); This will result in the final checking over of your classes and traits, and throw an exception if there is a problem. Some people may not object to this not-so-strict behavior, the smalltalk implementation of traits, written by the authors of the original papers behaves in a similar way. Here is a quote from a discussion I had with Nathanael Scharli, about the Smalltalk versions behavior: Well, in Squeak (as in the other Smalltalk dialects), the difference between runtime and compile time is not as clear as in most other programming languages. The reason for this is that programming in Smalltalk is very interactive and there is no explicit compile phase. This means that whenever a Smalltalk programmer adds or modifies a method, it gets immediately (and automatically) compiled and installed in the class. (Since Smalltalk is not statically typed, there are no type checks performed at compile time, and this is why compiling a method simply means creating and installing the byte-code of that method). However, I actually like if the programmer gets as much static information bout the code as possible. Therefore, my implementation automaticelly checks the open requirements whenever a method gets added/removed/modified. This means that in my implementation, the programmer gets interactive feedback about which requirements are still to be satisfied while he is composing the traits together. In particular, I also indicate when all the requirements of a class/trait are fulfilled. In case of classes, this means for the programmer that it is now possible to actually use the class without running into open requirements. However, according to the Smalltalk tradition, I do not prevent a programmer from instantiating a class that still has open requirements. (This can be useful if a programmer wants to test a certain functionality of a class before it is actually complete). Of course, there is then always the risk that there will be a runtime error because of an unsatisfied requirement. As a summary, I would say that my implementation of traits keeps track of the requirements at compile time. However, if an incomplete class (i.e., a class with open requirements) is instantiated, unfulfilled requirements result in a runtime error when they are called. =head1 TO DO I consider this implementation of Traits to be pretty much feature complete in terms of the description found in the papers. Of course improvements can always be made, below is a list of items on my to do list: =over 4 =item B I have revamped the test suite alot this time around. But it could always use more. Currently we have 158 tests in the suite. I ran it through Devel::Cover and found that the coverage is pretty good, but can use some help: ---------------------------- ------ ------ ------ ------ ------ ------ ------ File stmt branch cond sub pod time total ---------------------------- ------ ------ ------ ------ ------ ------ ------ /Class/Trait.pm 91.4 58.6 50.0 95.7 6.2 8.9 80.0 /Class/Trait/Base.pm 90.5 50.0 n/a 100.0 n/a 0.1 83.9 /Class/Trait/Config.pm 100.0 n/a n/a 100.0 100.0 2.9 100.0 ---------------------------- ------ ------ ------ ------ ------ ------ ------ Obviously Class::Trait::Config is fine. To start with Class::Trait::Reflection is not even tested at all. I am not totally happy with this API yet, so I am avoiding doing this for now. The pod coverage is really low in Class::Trait since virtually none of the methods are documented (as they are not public and have no need to be documented). The branch coverage is low too because of all the debug statements that are not getting execute (since we do not have DEBUG on). The branch coverage in Class::Trait::Base is somwhat difficult. Those are mostly rare error conditions and edge cases, none the less I would still like to test them. Mostly what remains that I would like to test is the error cases. I need to test that Class::Traits blows up in the places I expect it to. =item B Currently the work around for the mod_perl/INIT phase issue (see L) is to just let the unfufilled requirement routines fail normally with perl. Maybe I am a control freak, but I would like to be able to make these unfufilled methods throw my own exceptions instead. My solution was to make a bunch of stub routines for all the requirements. The problem is that I get a bunch of "subroutine redeined" warnings coming up when the local method definitions are installed by perl normally. Also, since we are installing our methods and our overloads into the class in the BEGIN phase now, it is possible that we will get subroutine redefinition errors if there is a local implementation of a method or operator. This is somewhat rare, so I am not as concerned about that now. Ideally I would like to find a way around the INIT issue, which will still have the elegance of using INIT. =item B The class Class::Traits::Reflection gives a basic API to access to the traits used by a class. Improvements can be made to this API as well as the information it supplies. =item B Being a relatively new concept, Traits can be difficult to digest and understand. The original papers does a pretty good job, but even they stress the usefulness of tools to help in the development and understanding of Traits. The 'debug' setting of Class::Trait gives a glut of information on every step of the process, but is only useful to a point. A Traits 'browser' is something I have been toying with, both as a command line tool and a Tk based tool. =item B In this release I have added some pre-built traits that can be used; TEquality, TComparable, TPrintable. I want to make more of these, it will only help. =back =head1 PRIVATE METHODS IN TRAITS Sometimes a trait will want to define private methods that only it can see. Any subroutine imported into the trait from outside of the trait will automatically be excluded. However, a trait can define private methods by using anonymous subroutines. package TSomeTrait; use Class::Trait 'base'; my $private = sub { ... }; sub public { my $self = shift; my $data = $self->$private; ... } =head1 ACKNOWLEDGEMENTS =over 4 =item * Curtis "Ovid" Poe Initial idea and code for this module. =item * Nathanael Scharli and the Traits research group. Answering some of my questions. =item * Yuval Kogman Spotting the problem with loading traits with :: in them. Thanks to Curtis "Ovid" Poe for bringing it up again, and prompting me to release the fix. =item * Roman Daniel Fixing SUPER:: handling. =item * Curtis "Ovid" Poe The code to change C to C. =back =head1 SEE ALSO Class::Trait is an implementation of Traits as described in the the documents found on this site L. In particular the paper "Traits - A Formal Model", as well as another paper on statically-typed traits (which is found here : L). =head1 ERROR MESSAGES =head2 Redefined subroutine warnings If a class using a trait has a method which the trait defines, the class's method is assumed to be the correct method. However, you should get a "Subroutine redefined" warning. To avoid this, explicitly exclude the method: use Class::Trait TSomeTrait => { exclude => 'foo' }; sub foo {} Sometimes you will see strange warnings such as: Subroutine Circle::(== redefined at /usr/lib/perl5/5.8.7/overload.pm at ... This is because traits can support overloading. To avoid this warning, define your overloaded methods prior to using L. use overload ( '==' => \&equalTo ); use Class::Trait "TCircle" => { exclude => 'equalTo' }, "TColor" => { exclude => 'equalTo' }; =head1 BUGS =head2 does When applying traits at runtime to instances, the following works: $object->does($some_trait_name); However, normally we should be able to do the following and get a list of all traits the instance does: my @does = $object->does; Currently, this returns no traits. It will be fixed in a future release. =head1 MAINTAINER Curtis "Ovid" Poe, C<< >> =head1 AUTHOR stevan little, Estevan@iinteractive.comE The development of this module was initially begun by Curtis "Ovid" Poe, Epoec@yahoo.comE. =head1 COPYRIGHT AND LICENSE Copyright 2004, 2005 by Infinity Interactive, Inc. L This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut Trait000755000765000765 011320064414 15474 5ustar00ovidovid000000000000Class-Trait-0.31/lib/ClassBase.pm000444000765000765 450211320064413 17041 0ustar00ovidovid000000000000Class-Trait-0.31/lib/Class/Traitpackage Class::Trait::Base; use strict; use warnings; require Class::Trait; our $VERSION = '0.31'; sub apply { my ($trait, $instance) = @_; Class::Trait->apply($instance, $trait); return $trait; } # all that is here is an AUTOLOAD method which is used to fix the SUPER call # method resolution problem introduced when a trait calls a method in a SUPER # class since SUPER should be bound after the trait is flattened and not # before. sub AUTOLOAD { my $auto_load = our $AUTOLOAD; # we dont want to mess with DESTORY return if ( $auto_load =~ m/DESTROY/ ); # if someone is attempting a call to # SUPER, then we need to handle this. if ( my ($super_method) = $auto_load =~ /(SUPER::.*)/ ) { # get our arguemnts my ( $self, @args ) = @_; # lets get the intended method name $super_method = scalar( caller 1 ) . '::' . $super_method; return $self->$super_method(@args); } # if it was not a call to SUPER, then # we need to let this fail, as it is # not our problem die "undefined method ($auto_load) in trait\n"; } 1; __END__ =head1 NAME Class::Trait::Base - Base class for all Traits =head1 SYNOPSIS This class needs to be inherited by all traits so they can be identified as traits. use Class::Trait 'base'; =head1 DESCRIPTION Not much going on here, just an AUTOLOAD method to help properly dispatch calls to C and an C method. ############################################################################## =head2 apply require TSomeTrait; TSomeTrait->apply($object); This method allows you to apply a trait to an object. It returns the trait so you can then reapply it: TTricks->apply($dog_object) ->apply($cat_object); This is merely syntactic sugar for the C method: Class::Trait->apply($dog_object, 'TTricks'); Class::Trait->apply($cat_object, 'TTricks'); =cut =head1 SEE ALSO B, B =head1 MAINTAINER Curtis "Ovid" Poe, C<< >> =head1 AUTHOR Stevan Little Estevan@iinteractive.comE =head1 COPYRIGHT AND LICENSE Copyright 2004, 2005 by Infinity Interactive, Inc. L This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut Config.pm000444000765000765 634211320064415 17402 0ustar00ovidovid000000000000Class-Trait-0.31/lib/Class/Traitpackage Class::Trait::Config; use strict; use warnings; use base qw(Class::Accessor::Fast); our $VERSION = '0.31'; # we are going for a very struct-like class here to try and keep the # syntactical noise down. # We never intend this class to be subclassed, so the constructor is very # simple on purpose. you can consider this class to be effectively sealed. sub new { my $class = shift; return bless { name => "", sub_traits => [], requirements => {}, methods => {}, overloads => {}, conflicts => {} }, $class; } __PACKAGE__->mk_accessors(qw( name sub_traits requirements methods overloads conflicts )); # a basic clone function for moving in and out of the cache. sub clone { my $self = shift; my $class = ref $self; return bless { name => $self->{name}, sub_traits => [ @{ $self->{sub_traits} } ], requirements => { %{ $self->{requirements} } }, methods => { %{ $self->{methods} } }, overloads => { %{ $self->{overloads} } }, conflicts => { %{ $self->{conflicts} } }, }, $class; } 1; __END__ =head1 NAME Class::Trait::Config - Trait configuration information storage package. =head1 SYNOPSIS This package is used internally by Class::Trait to store Trait configuration information. It is also used by Class::Trait::Reflection to gather information about a Trait. =head1 DESCRIPTION This class is a intentionally very C-struct-like. It is meant to help encapsulate the Trait configuration information in a clean easy to access way. This class is effectively sealed. It is not meant to be extended, only to be used. =head1 METHODS =over 4 =item B Creates a new empty Class::Trait::Config object, with fields initialized to empty containers. =item B An accessor to the C string field of the Class::Trait::Config object. =item B An accessor to the C array reference field of the Class::Trait::Config object. =item B An accessor to the C hash reference field of the Class::Trait::Config object. Note, the requirements field is a hash reference to speed requirement lookup, the values of the hash are simply booleans. =item B An accessor to the C hash reference field of the Class::Trait::Config object. =item B An accessor to the C hash reference field of the Class::Trait::Config object. =item B An accessor to the C hash reference field of the Class::Trait::Config object. Note, the conflicts field is a hash reference to speed conflict lookup, the values of the hash are simply booleans. =item B Provides deep copy functionality for the Class::Trait::Config object. This will be sure to copy all sub-elements of the object, but not to attempt to copy and subroutine references found. =back =head1 SEE ALSO B, B =head1 AUTHOR Stevan Little Estevan@iinteractive.comE =head1 COPYRIGHT AND LICENSE Copyright 2004, 2005 by Infinity Interactive, Inc. L This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut Reflection.pm000444000765000765 1365711320064413 20314 0ustar00ovidovid000000000000Class-Trait-0.31/lib/Class/Traitpackage Class::Trait::Reflection; use strict; use warnings; our $VERSION = '0.31'; use Class::Trait (); # constructor sub new { my ( $_class, $_package_or_trait ) = @_; my $class = ref($_class) || $_class; no strict 'refs'; # accept a package or an object my ( $_trait, $package ); if ( ref($_package_or_trait) && $_package_or_trait->isa("Class::Trait::Config") ) { $_trait = $_package_or_trait; $package = $_trait->name(); } else { $package = ref($_package_or_trait) || $_package_or_trait; $_trait = ${"${package}::TRAITS"}->clone(); } # we are gonna do that symbol table thang my $trait = { package_name => $package, # we want to clone the trait so that # we can mess with it if we want trait => $_trait }; bless $trait, $class; return $trait; } # methods # accessors sub getName { my ($self) = @_; return $self->{trait}->name(); } sub getSubTraitList { my ($self) = @_; return wantarray ? @{ $self->{trait}->sub_traits() } : $self->{trait}->sub_traits(); } sub getRequirements { my ($self) = @_; return wantarray ? keys %{ $self->{trait}->requirements() } : [ keys %{ $self->{trait}->requirements() } ]; } sub getMethods { my ($self) = @_; return $self->{trait}->methods(); } sub getMethodLabels { my ($self) = @_; return wantarray ? keys %{ $self->{trait}->methods } : [ keys %{ $self->{trait}->methods } ]; } sub getConflicts { my ($self) = @_; return wantarray ? keys %{ $self->{trait}->conflicts() } : [ keys %{ $self->{trait}->conflicts() } ]; } sub getOverloads { my ($self) = @_; return $self->{trait}->overloads(); } sub getOperators { my ($self) = @_; return wantarray ? keys %{ $self->{trait}->overloads } : [ keys %{ $self->{trait}->overloads } ]; } # other methods sub loadSubTraitByName { my ( $self, $trait_name ) = @_; return $self->new( Class::Trait::load_trait($trait_name) ); } sub getTraitDump { my ($self) = @_; require Data::Dumper; return Data::Dumper::Dumper( { %{ $self->{trait} } } ); } sub traverse { my ( $trait, $function, $depth ) = @_; $depth ||= 0; $function->( $trait, $depth ); foreach my $sub_trait_name ( $trait->getSubTraitList() ) { my $sub_trait = $trait->loadSubTraitByName($sub_trait_name); $sub_trait->traverse( $function, $depth + 1 ); } } 1; __END__ =head1 NAME Class::Trait::Reflection - Reflection class used to find information about classes which use Traits. =head1 SYNOPSIS The Class::Trait::Reflection class used to find information about classes which use Traits. =head1 DESCRIPTION This class is to be used by other applications as a foundation from which to build various trait compostion tools. It attempts to decouple others from the internal representation of traits (currently the Class::Trait::Config object) and provide a more abstract view of them. =head1 METHODS =head2 constructor =over 4 =item B If given either a I, I or I. This constructor will return a valid Class::Trait::Reflection object which can be used to examine the specific properties of the traits utilized. =back =head2 accessors =over 4 =item B Returns the name string for the trait. =item B Returns an array or an array ref in scalar context) of string names of all the sub-traits the trait includes. =item B Returns an array (or an array ref in scalar context) of method labels and operators which represent the requirements for the given trait. =item B Returns an hash ref of method label strings to method subroutine references. =item B Returns an array (or an array ref in scalar context) of method label strings. =item B Returns an array (or an array ref in scalar context) of method labels and operators which are in conflict for a given trait. This is only applicable for COMPOSITE traits. =item B Returns an hash ref of operators to method label strings. =item B Returns an array (or an array ref in scalar context) of all the operators for a given trait. =back =head2 Utility methods =over 4 =item B Given a trait name, this method attempts to load the trait using the Class::Trait module, and then uses that trait to construct a new Class::Trait::Reflection object to examine the trait with. This can function both as a class method and an instance method. =item B Returns a Data::Dumper string of the internals of a Class::Trait::Config object. =item B Given a subroutine reference, this method can be used to traverse a trait heirarchy. The subroutine reference needs to take two parameters, the first is the current trait being examined, the second is the number representing the depth within the trait heirarchy. Here is an example of printing out the trait heirarchy as tabbed in names: my $reflected_trait = Class::Trait::Reflection->new($object_or_package); $reflected_trait->traverse(sub { my ($trait, $depth) = @_; print((" " x $depth), $trait->getName(), "\n"); }); This should produce output similar to this: COMPOSITE TCircle TMagnitude TEquality TGeometry TColor TEquality Note: COMPOSITE is the placeholder name for an unnamed composite trait such as the one found in a class. =back =head1 SEE ALSO B, B =head1 AUTHOR Stevan Little Estevan@iinteractive.comE =head1 COPYRIGHT AND LICENSE Copyright 2004, 2005 by Infinity Interactive, Inc. L This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut Lib000755000765000765 011320064414 16202 5ustar00ovidovid000000000000Class-Trait-0.31/lib/Class/TraitTComparable.pm000444000765000765 414211320064414 21067 0ustar00ovidovid000000000000Class-Trait-0.31/lib/Class/Trait/Libpackage TComparable; use strict; use warnings; our $VERSION = '0.31'; ## we are a trait use Class::Trait 'base'; use Class::Trait qw(TEquality); ## overload operator our %OVERLOADS = ( '<=>' => "compare" ); ## requires methods our @REQUIRES = qw(compare); ### methods # The equals method is there to provide # specific handler for the '==' operator (and # to be sure about how '!=' will react, we # override the autogeneration with the _notEquals # method). # This is here so that one can deal with '==' and '!=' # and not the '<', '<=', '<=>', '=>', '>' operators. # NOTE: # Our default implementation of equals actually defers # to the compare method, and the _notEquals method # actually defers to the value of equals (and returns # the inverse), so that an object which wants all # the operators ('<=>' and co.) will be able to use # the '==' and '!=' operators without an issue. # If however compare is not defined, a # MethodNotImplemented exception will be thrown. # This retains backwards compatability while still # allowing for specialization. sub equalTo { my ( $left, $right ) = @_; return ( $left->compare($right) == 0 ) ? 1 : 0; } 1; __END__ =head1 NAME TComparable - Trait for adding comparison abilities to your object =head1 DESCRIPTION This trait gives your object a wide range of comparison abilities through its overloading of the E=E operator. =head1 SUB-TRAITS =over 4 =item B =back =head1 REQUIRES =over 4 =item B This method should return -1 if C<$left> is less than C<$right>, 0 if C<$left> is equal to C<$right>, and 1 if C<$left> is greater than C<$right>. =back =head1 OVERLOADS =over 4 =item B=E> =back =head1 PROVIDES =over 4 =item B This fufills the requirement of the sub-trait TEquality. =back =head1 AUTHOR Stevan Little Estevan@iinteractive.comE =head1 COPYRIGHT AND LICENSE Copyright 2004, 2005 by Infinity Interactive, Inc. L This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut TEquality.pm000444000765000765 646211320064414 20626 0ustar00ovidovid000000000000Class-Trait-0.31/lib/Class/Trait/Libpackage TEquality; use strict; use warnings; our $VERSION = '0.31'; use Class::Trait 'base'; our %OVERLOADS = ( '==' => "equalTo", '!=' => "notEqualTo" ); our @REQUIRES = ("equalTo"); sub notEqualTo { my ( $left, $right ) = @_; return not $left->equalTo($right); } sub isSameTypeAs { my ( $left, $right ) = @_; # we know the left operand is an object right operand must be an object # and either right is derived from the same type as left or left is # derived from the same type as right return ( ref($right) && ( $right->isa( ref($left) ) || $left->isa( ref($right) ) ) ); } # this method attempts to decide if an object is exactly the same as one # another. It does this by comparing the Perl built-in string representations # of a reference and displays the object's memory address. sub isExactly { my ( $self, $candidate ) = @_; # $candidate must also be a Comparable object, otherwise there is no way # they can be the same. Along the same veins, we can check very quickly # to see if we are dealing with the same objects by testing the values # returned by ref(), for if they are not the same, then again, this fails. return 0 unless ref($self) eq ref($candidate); # from now on this gets a little trickier... First we need to test if the # objects are Printable, since this will prevent us from being able to get # a proper string representation of the object's memory address through # normal stringification, and so we will need to call its method # stringValue (see the Printable interface for more info) return ( $self->stringValue() eq $candidate->stringValue() ) if $self->does("TPrintable"); # if the object is not Printable, that means that we can use the built in # Perl stringification routine then, so we do just that, if these strings # match then the memory address will match as well, and we will know we # have the exact same object. return ( "$self" eq "$candidate" ); } 1; __END__ =head1 NAME TEquality - Trait for adding equality testing to your object =head1 DESCRIPTION TEquality adds a number of equality testing features, including type-equality as well as object instance equality. =head1 REQUIRES =over 4 =item B The C method is expected to return either true if its two arguments are equal (by whatever standards your devise), or false if they are not. =back =head1 OVERLOADS =over 4 =item B<==> =item B =back =head1 PROVIDES =over 4 =item B This is the inverse of C. =item B This will determine type equality, meaning it will determine if both arguements are derived from the same type. =item B This will attempt to discern whether or not the two arguments given are the same object. It even takes into account the possibility that the objects might also have utilized the TPrintable trait, and so works around that automatic stringification. =back =head1 AUTHOR Stevan Little Estevan@iinteractive.comE =head1 COPYRIGHT AND LICENSE Copyright 2004, 2005 by Infinity Interactive, Inc. L This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut TPrintable.pm000444000765000765 242311320064413 20741 0ustar00ovidovid000000000000Class-Trait-0.31/lib/Class/Trait/Libpackage TPrintable; use strict; use warnings; our $VERSION = '0.31'; use Class::Trait 'base'; use overload (); # we need a method from overload ## overload operator our %OVERLOADS = ( '""' => "toString" ); ## requires our @REQUIRES = qw(toString); ### methods # return the unmolested object string sub stringValue { my ($self) = @_; return overload::StrVal($self); } 1; __END__ =head1 NAME TPrintable - Trait for adding stringification abilities to your object =head1 DESCRIPTION TPrintable gives your object automatic stringification abilities, as well as access to your original stringified object value. =head1 REQUIRES =over 4 =item B This method should return the stringified object. =back =head1 OVERLOADS =over 4 =item B<""> This operator call the C method to stringify the object. =back =head1 PROVIDES =over 4 =item B This returns the normal perl stringified value, bypassing whatever C might return. =back =head1 AUTHOR Stevan Little Estevan@iinteractive.comE =head1 COPYRIGHT AND LICENSE Copyright 2004, 2005 by Infinity Interactive, Inc. L This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut t000755000765000765 011320064414 13041 5ustar00ovidovid000000000000Class-Trait-0.31010_class_trait.t000555000765000765 330011320064413 16251 0ustar00ovidovid000000000000Class-Trait-0.31/t#!/usr/bin/perl use strict; use warnings; use Test::More tests => 22; BEGIN { unshift @INC => ( 't/test_lib', '/test_lib' ); } # we have to use it directly because it uses an INIT block to flatten traits use BasicTrait; can_ok( BasicTrait => 'getName' ); is( BasicTrait->getName(), 'TSimple', '... and it should have the method from the trait' ); ok( BasicTrait->does("TSimple"), '.. BasicTrait is TSimple' ); ok( exists( $BasicTrait::{"TRAITS"} ), '... the $TRAITS are properly stored' ); my $trait; { no strict 'refs'; # get the trait out $trait = ${"BasicTrait::TRAITS"}; } # check to see what it is isa_ok( $trait, 'Class::Trait::Config' ); # now examine the trait itself can_ok( $trait, 'name' ); is( $trait->name, 'TSimple', '... get the traits name' ); can_ok( $trait, 'sub_traits' ); is( ref( $trait->sub_traits ), "ARRAY", '... our sub_trait is an array ref' ); ok( eq_array( $trait->sub_traits, [] ), '... both should be empty' ); can_ok( $trait, 'requirements' ); is( ref( $trait->requirements ), "HASH", '... our requirements is an hash ref' ); ok( eq_hash( $trait->requirements, {} ), '... both should be empty' ); can_ok( $trait, 'overloads' ); is( ref( $trait->overloads ), "HASH", '... our overloads is an hash ref' ); ok( eq_hash( $trait->overloads, {} ), '... both should be empty' ); can_ok( $trait, 'conflicts' ); is( ref( $trait->conflicts ), "HASH", '... our conflicts is an hash ref' ); ok( eq_hash( $trait->conflicts, {} ), '... both should be empty' ); can_ok( $trait, 'methods' ); is( ref( $trait->methods ), "HASH", '... our methods is an hash ref' ); ok( eq_hash( $trait->methods, { "getName" => 'TSimple::getName' } ), '... both should NOT be empty' ); 020_test_imports.t000444000765000765 371311320064414 16504 0ustar00ovidovid000000000000Class-Trait-0.31/t#!/usr/bin/perl use strict; use warnings; use Test::More tests => 25; BEGIN { unshift @INC => ( 't/test_lib', '/test_lib' ); } # we have to use it directly because it uses an INIT block to flatten traits use BasicTraitImport; can_ok( BasicTraitImport => 'getName' ); is( BasicTraitImport->getName(), 'TImport', '... and it should have the method from the trait' ); ok( BasicTraitImport->does("TImport"), '.. BasicTraitImport is TImport' ); ok( exists( $BasicTraitImport::{"TRAITS"} ), '... the $TRAITS are properly stored' ); my $trait; { no strict 'refs'; # get the trait out $trait = ${"BasicTraitImport::TRAITS"}; } # check to see what it is isa_ok( $trait, 'Class::Trait::Config' ); # now examine the trait itself can_ok( $trait, 'name' ); is( $trait->name, 'TImport', '... get the traits name' ); can_ok( $trait, 'sub_traits' ); is( ref( $trait->sub_traits ), "ARRAY", '... our sub_trait is an array ref' ); ok( eq_array( $trait->sub_traits, [] ), '... both should be empty' ); can_ok( $trait, 'requirements' ); is( ref( $trait->requirements ), "HASH", '... our requirements is an hash ref' ); ok( eq_hash( $trait->requirements, {} ), '... both should be empty' ); can_ok( $trait, 'overloads' ); is( ref( $trait->overloads ), "HASH", '... our overloads is an hash ref' ); ok( eq_hash( $trait->overloads, {} ), '... both should be empty' ); can_ok( $trait, 'conflicts' ); is( ref( $trait->conflicts ), "HASH", '... our conflicts is an hash ref' ); ok( eq_hash( $trait->conflicts, {} ), '... both should be empty' ); can_ok( $trait, 'methods' ); is( ref( $trait->methods ), "HASH", '... our methods is an hash ref' ); ok( eq_hash( $trait->methods, { "getName" => 'TImport::getName' } ), '... both should NOT be empty' ); can_ok 'TImport', 'getName'; # XXX note that even though these methods are here, they are not considered # "provided" methods by the trait because the trait imported them. can_ok 'TImport', 'this'; can_ok 'TImport', 'that'; 030_trait_overload.t000555000765000765 1046711320064413 17015 0ustar00ovidovid000000000000Class-Trait-0.31/t#!/usr/bin/perl use strict; use warnings; use Test::More tests => 49; use overload (); BEGIN { unshift @INC => ( 't/test_lib', '/test_lib' ); } # we have to use it directly because it uses an INIT block to flatten traits use TraitTest; can_ok( "TraitTest", 'new' ); my $trait_1 = TraitTest->new(3); my $trait_2 = TraitTest->new(3); isa_ok( $trait_1, 'TraitTest' ); isa_ok( $trait_1, 'TraitTestBase' ); isa_ok( $trait_2, 'TraitTest' ); isa_ok( $trait_2, 'TraitTestBase' ); ok( $trait_1->does("TPrintable"), '... trait 1 is TPrintable' ); ok( $trait_1->does("TCompositeTest"), '... trait 1 is TCompositeTest' ); ok( $trait_1->does("TComparable"), '... trait 1 is TComparable (because of TCompositeTest' ); ok( $trait_2->does("TPrintable"), '... trait 2 is TPrintable' ); ok( $trait_2->does("TCompositeTest"), '... trait 2 is TCompositeTest' ); ok( $trait_2->does("TComparable"), '... trait 2 is TComparable (because of TCompositeTest' ); # check that it "can" execute the methods # that it should have gotten from the traits foreach my $method ( qw/ compositeTestRequirement compositeTest /, # from CompositeTest qw/ toString stringValue /, # from TPrintable qw/ compare equalTo notEqualTo /, # from TComparable ) { can_ok( $trait_1, $method ); can_ok( $trait_2, $method ); } # test the aliased method strVal can_ok( $trait_1, 'strVal' ); can_ok( $trait_2, 'strVal' ); # check overloads as well.... # for TComparable ok( overload::Method( $trait_1, '==' ), '... trait 1 overload ==' ); ok( overload::Method( $trait_1, '!=' ), '... trait 1 overload !=' ); ok( overload::Method( $trait_1, '<=>' ), '... trait 1 overload <=>' ); # for TPrintable ok( overload::Method( $trait_1, '""' ), '... trait 1 overload ""' ); # for TComparable ok( overload::Method( $trait_2, '==' ), '... trait 2 overload ==' ); ok( overload::Method( $trait_2, '!=' ), '... trait 2 overload !=' ); ok( overload::Method( $trait_2, '<=>' ), '... trait 2 overload <=>' ); # for TPrintable ok( overload::Method( $trait_2, '""' ), '... trait 2 overload ""' ); # now check if they behave as we expect # check "" operator from TPrintable is( "$trait_1", '3.000 (overridden stringification)', '... and it should be stringified correctly' ); is( "$trait_2", '3.000 (overridden stringification)', '... and it should be stringified correctly' ); # check == operator from TComparable # XXX using cmp_ok generates correct, but irrelevent "not numeric" warnings ok( $trait_1 == $trait_2, '... and they should be equal' ); # check != operator from TComparable ok( !( $trait_1 != $trait_2 ), '... and they shouldnt be not equal' ); # check the compare <=> operator cmp_ok( ( $trait_1 <=> $trait_2 ), '==', 0, '... and they shouldnt be equal and therefore <=> return 0' ); # check the aliased stringValue function like( $trait_1->strVal, qr/TraitTest=HASH\(0x[a-fA-F0-9]+\)/, '... and should return a reasonable strVal' ); like( $trait_2->strVal, qr/TraitTest=HASH\(0x[a-fA-F0-9]+\)/, '... and should return a reasonable strVal' ); # now lets extract the actul trait and examine it my $trait; { no strict 'refs'; # get the trait out $trait = ${"TraitTest::TRAITS"}; } # check to see it is what we want it to be isa_ok( $trait, 'Class::Trait::Config' ); # now examine the trait itself is( $trait->name, 'COMPOSITE', '... get the traits name' ); ok( eq_array( $trait->sub_traits, [ 'TCompositeTest', 'TPrintable' ] ), '... this should not be empty' ); ok( eq_hash( $trait->conflicts, {} ), '... this should be empty' ); ok( eq_hash( $trait->requirements, { compare => 1, compositeTestRequirement => 1, toString => 2 # this was required twice } ), '... this should not be empty' ); ok( eq_hash( $trait->overloads, { '<=>' => 'compare', '==' => 'equalTo', '""' => 'toString', '!=' => 'notEqualTo' } ), '... this should not be empty' ); ok( eq_set( [ keys %{ $trait->methods } ], [ 'stringValue', 'compositeTest', 'strVal', 'equalTo', 'notEqualTo', 'isSameTypeAs', 'isExactly' ] ), '... this should not be empty' ); 040_trait_composition.t000555000765000765 666011320064414 17527 0ustar00ovidovid000000000000Class-Trait-0.31/t#!/usr/bin/perl use strict; use warnings; use Test::More tests => 41; use Test::Differences; BEGIN { chdir 't' if -d 't'; unshift @INC => ( 'test_lib', '../lib' ); } # we have to use it directly because it uses an INIT block to flatten traits use Circle; # create a circle can_ok( "Circle", "new" ); my $circle = Circle->new(); # make sure it is a Circle isa_ok( $circle, 'Circle' ); # check the traits in it my @trait_in_circle = qw( TCircle TColor TEquality TGeometry TMagnitude ); ok( $circle->does($_), "... circle does $_" ) foreach @trait_in_circle; is_deeply [ sort $circle->does ], \@trait_in_circle, 'Calling does() without an argument should return all traits'; ok my $tcircle_config = Class::Trait->fetch_trait_from_cache('TCircle'), 'We should be able to fetch a traits configuration from the cache'; # now check the methods we expect it to have my @method_labels = ( qw/ notEqualTo isSameTypeAs /, # TEquality qw/ lessThanOrEqualTo greaterThan greaterThanOrEqualTo isBetween / , # TMagnitude qw/ area bounds diameter scaleBy /, # TGeometry qw/ getRed setRed getBlue setBlue getGreen setGreen equalTo /, # TColor qw/ lessThan equalTo /, # TCircle ); can_ok( $circle, $_ ) foreach @method_labels; # now check the overloaded operators we expect it to have # for Circle ok( overload::Method( $circle, '==' ), '... circle overload ==' ); # for TCircle # NOTE: TCircle overloads == too, but Circle overrides that ok( overload::Method( $circle, '<' ), '... circle overload <' ); # for TEquality # NOTE: TEquality overloads == too, but Circle overrides that ok( overload::Method( $circle, '!=' ), '... circle overload !=' ); # for TMagnitude # NOTE: TMagnitude overloads < too, but TCircle overrides that ok( overload::Method( $circle, '<=' ), '... circle overload <=' ); ok( overload::Method( $circle, '>' ), '... circle overload >' ); ok( overload::Method( $circle, '>=' ), '... circle overload >=' ); # now lets extract the actul trait and examine it my $trait; { no strict 'refs'; # get the trait out $trait = ${"Circle::TRAITS"}; } # check to see it is what we want it to be isa_ok( $trait, 'Class::Trait::Config' ); # now examine the trait itself is( $trait->name, 'COMPOSITE', '... get the traits name' ); eq_or_diff $trait->sub_traits, [ 'TCircle', 'TColor' ], '... this should not be empty'; eq_or_diff $trait->conflicts, {}, '... we should have no conflicts'; eq_or_diff $trait->requirements, { getRadius => 1, setRadius => 1, getRGB => 1, setRGB => 1, getCenter => 1, setCenter => 1, equalTo => 2, }, '... and trait requirements should be correct'; eq_or_diff $trait->overloads, { '==' => 'equalTo', '>=' => 'greaterThanOrEqualTo', '<=' => 'lessThanOrEqualTo', '>' => 'greaterThan', '<' => 'lessThan', '!=' => 'notEqualTo' }, '... and the overloaded operators should be correct'; eq_or_diff [ sort keys %{ $trait->methods } ], [ qw( area bounds diameter getBlue getGreen getRed greaterThan greaterThanOrEqualTo isBetween isExactly isSameTypeAs lessThan lessThanOrEqualTo notEqualTo scaleBy setBlue setGreen setRed ) ], '... and the trait methods should also be correct'; 050_Trait_Config_test.t000444000765000765 621011320064413 17354 0ustar00ovidovid000000000000Class-Trait-0.31/t#!/usr/bin/perl use strict; use warnings; use Test::More tests => 34; BEGIN { unshift @INC => ( 't/test_lib', '/test_lib' ); use_ok("Class::Trait::Config"); } can_ok( "Class::Trait::Config", 'new' ); my $trait_config = Class::Trait::Config->new(); isa_ok( $trait_config, 'Class::Trait::Config' ); # check the expected contents of an # empty Class::Trait::Config object can_ok( $trait_config, 'name' ); ok( !$trait_config->name ); can_ok( $trait_config, 'sub_traits' ); is( ref( $trait_config->sub_traits ), "ARRAY", '... its an array reference' ); ok( eq_array( $trait_config->sub_traits, [] ), '... both should be empty' ); can_ok( $trait_config, 'requirements' ); is( ref( $trait_config->requirements ), "HASH", '... its an hash reference' ); ok( eq_hash( $trait_config->requirements, {} ), '... both should be empty' ); can_ok( $trait_config, 'methods' ); is( ref( $trait_config->methods ), "HASH", '... its an hash reference' ); ok( eq_hash( $trait_config->methods, {} ), '... both should be empty' ); can_ok( $trait_config, 'overloads' ); is( ref( $trait_config->overloads ), "HASH", '... its an hash reference' ); ok( eq_hash( $trait_config->overloads, {} ), '... both should be empty' ); can_ok( $trait_config, 'conflicts' ); is( ref( $trait_config->conflicts ), "HASH", '... its an hash reference' ); ok( eq_hash( $trait_config->conflicts, {} ), '... both should be empty' ); # create some variables to put # into the $trait_config object my $name = "Trait Config Test"; my $sub_traits = [ "Sub Trait Test 1", "Sub Trait Test 2" ]; my $requirements = { "test" => 1 }; my $methods = { "untest" => sub { not $_[0]->test() } }; my $overloads = { "==" => 1, "!=" => 1 }; my $conflicts = { "toString" => 1 }; # add in those same variables $trait_config->name($name); $trait_config->sub_traits($sub_traits); $trait_config->requirements($requirements); $trait_config->methods($methods); $trait_config->overloads($overloads); $trait_config->conflicts($conflicts); # now test that they were successfully inserted is( $trait_config->name, $name, '... it should assigned now' ); is( ref( $trait_config->sub_traits ), "ARRAY", '... its an array reference' ); ok( eq_array( $trait_config->sub_traits, $sub_traits ), '... both should not be empty' ); is( ref( $trait_config->requirements ), "HASH", '... its an hash reference' ); ok( eq_hash( $trait_config->requirements, $requirements ), '... both should not be empty' ); is( ref( $trait_config->methods ), "HASH", '... its an hash reference' ); ok( eq_hash( $trait_config->methods, $methods ), '... both should not be empty' ); is( ref( $trait_config->overloads ), "HASH", '... its an hash reference' ); ok( eq_hash( $trait_config->overloads, $overloads ), '... both should not be empty' ); is( ref( $trait_config->conflicts ), "HASH", '... its an hash reference' ); ok( eq_hash( $trait_config->conflicts, $conflicts ), '... both should not be empty' ); # clone test can_ok( $trait_config, 'clone' ); my $trait_config_clone = $trait_config->clone(); isa_ok( $trait_config_clone, 'Class::Trait::Config' ); isnt( $trait_config, $trait_config_clone, '... these should be different' ); 060_Trait_SUPER_test.t000444000765000765 243111320064414 17050 0ustar00ovidovid000000000000Class-Trait-0.31/t#!/usr/bin/perl use strict; use warnings; use Test::More tests => 14; BEGIN { unshift @INC => ( 't/test_lib', '/test_lib' ); } use Read; use SyncRead; can_ok( "Read", 'new' ); my $reader = Read->new(); isa_ok( $reader, 'Read' ); can_ok( "SyncRead", 'new' ); my $sync_reader = SyncRead->new(); isa_ok( $sync_reader, 'SyncRead' ); isa_ok( $sync_reader, 'Read' ); ok( $sync_reader->does('TSyncRead'), '... sync reader is a TSyncRead' ); # these should be the same is( $reader->read(), $sync_reader->read(), '... these should be the same results' ); # now lets extract the actul trait and examine it my $trait; { no strict 'refs'; # get the trait out $trait = ${"SyncRead::TRAITS"}; } # check to see it is what we want it to be isa_ok( $trait, 'Class::Trait::Config' ); # now examine the trait itself is( $trait->name, 'TSyncRead', '... get the traits name' ); ok( eq_array( $trait->sub_traits, [] ), '... this should be empty' ); ok( eq_hash( $trait->conflicts, {} ), '... this should be empty' ); ok( eq_hash( $trait->overloads, {} ), '... this should be empty' ); ok( eq_hash( $trait->requirements, { read => 1 } ), '... this should not be empty' ); ok( eq_set( [ keys %{ $trait->methods } ], [ 'lock', 'unlock', 'read' ] ), '... this should not be empty' ); 070_Trait_mod_perl_test.t000444000765000765 121511320064414 17753 0ustar00ovidovid000000000000Class-Trait-0.31/t#!/usr/bin/perl use strict; use warnings; use Test::More tests => 2; BEGIN { unshift @INC => ( 't/test_lib', '/test_lib' ); } # NOTE: # This test proves that traits can work under mod_perl, if care is taken about # how things are loaded. All traits should be imported from within your # startup file, and then the Class::Trait->initialize() method should be # called after all are loaded. This should result in the correct behavior. my $warn; local $SIG{__WARN__} = sub { $warn = shift }; eval "use BasicTrait;"; ok ! defined $warn, 'mod_perl should no longer warn on startup'; ok( BasicTrait->does("TSimple"), '.. BasicTrait is TSimple' ); 080_Trait_SUPER2_test.t000444000765000765 64711320064414 17123 0ustar00ovidovid000000000000Class-Trait-0.31/t#!/usr/bin/perl # Tests the class inherited from traited class which trait uses SUPER use strict; use warnings; use Test::More tests => 3; BEGIN { unshift @INC => ( 't/test_lib', '/test_lib' ); } use Employee; my $pt = PersonWithTitle->new; my $e = Employee->new; my $p = Person->new; is( $pt->name, 'Mgr. George Richardson' ); is( $p->name, 'George Richardson' ); is( $e->name, 'Mgr. George Richardson' ); 090_Class_Trait_Lib_tests.t000444000765000765 606111320064413 20175 0ustar00ovidovid000000000000Class-Trait-0.31/t#!/usr/bin/perl use strict; use warnings; use Test::More tests => 20; BEGIN { unshift @INC => ('t'); } # this will test if BEGIN { package Test::Class::LoadingTraitsWithColonsInThem; use Class::Trait qw(Test::LoadingTraitsWithColonsInThem); sub new { bless {} } } { can_ok( "Test::Class::LoadingTraitsWithColonsInThem", 'new' ); my $test = Test::Class::LoadingTraitsWithColonsInThem->new(); can_ok( $test, 'does' ); ok( $test->does('Test::LoadingTraitsWithColonsInThem'), '... our trait was compiled successfully' ); can_ok( $test, 'isLoaded' ); is( $test->isLoaded(), 'Test::LoadingTraitsWithColonsInThem', '... and our trait method is as we expected' ); } BEGIN { package Test::Class::Another::ColonInTheName; use Class::Trait qw(Test::Another::ColonInTheName); sub new { bless {} } } { can_ok( "Test::Class::Another::ColonInTheName", 'new' ); my $test = Test::Class::Another::ColonInTheName->new(); can_ok( $test, 'does' ); ok( $test->does('Test::Another::ColonInTheName'), '... our trait was compiled successfully' ); can_ok( $test, 'isLoaded' ); is( $test->isLoaded(), 'Test::Another::ColonInTheName', '... and our trait method is as we expected' ); } # test some of the Trait lib { package Test::TEquality; use Class::Trait qw(TEquality); sub new { my ( $class, $num ) = @_; return bless { num => $num }, $class; } sub equalTo { my ( $left, $right ) = @_; if ( ref($right) ) { return $left->{num} == $right->{num}; } else { return $left->{num} == $right; } } } # test TEquality { my $test1 = Test::TEquality->new(5); my $test2 = Test::TEquality->new(5); my $test3 = Test::TEquality->new(10); ok( ( $test1 == $test2 ), '... our values compare correctly' ); ok( ( $test2 == 5 ), '... our values compare correctly' ); ok( ( $test1 != $test3 ), '... our values compare correctly' ); ok( $test1->isSameTypeAs($test2), '... our objects are the same type' ); ok( !$test1->isSameTypeAs("test"), '... our objects are not the same type' ); ok( $test1->isExactly($test1), '... our objects are the same type' ); ok( !$test1->isExactly($test2), '... our objects not are the same type' ); } { package Test::TComparable; use Class::Trait qw(TComparable); sub new { my ( $class, $num ) = @_; return bless { num => $num }, $class; } sub compare { my ( $left, $right ) = @_; return $left->{num} <=> $right->{num}; } } { my $test1 = Test::TComparable->new(1); my $test2 = Test::TComparable->new(5); my $test3 = Test::TComparable->new(10); my @sorted = sort { $a <=> $b } $test3, $test1, $test2; is( "$sorted[0]", "$test1", '... got the right first item' ); is( "$sorted[1]", "$test2", '... got the right second item' ); is( "$sorted[2]", "$test3", '... got the right third item' ); } 100_trait_rename_does.t000555000765000765 1275311320064414 17462 0ustar00ovidovid000000000000Class-Trait-0.31/t#!/usr/bin/perl use strict; use warnings; { package Not::main; # this is imported into a different package to avoid conflicts with "is()" use Test::More tests => 52; } use overload (); BEGIN { unshift @INC => ( 't/test_lib', '/test_lib' ); # we have to require Class::Trait to avoid importing # and it must be in a BEGIN block to ensure that rename_does # fires before the does() method is installed require Class::Trait; Test::More::can_ok 'Class::Trait', 'rename_does'; eval { Class::Trait->rename_does('$$') }; Test::More::like $@, qr/Illegal name for trait relation method \(\$\$\)/, '... calling rename_does() with an illegal method name should die'; Test::More::ok +Class::Trait->rename_does('is'), '... but calling it with a legal method name should succeed'; } # we have to use it directly because it uses an INIT block to flatten traits use TraitTest; Test::More::can_ok( "TraitTest", 'new' ); my $trait_1 = TraitTest->new(3); my $trait_2 = TraitTest->new(3); Test::More::isa_ok( $trait_1, 'TraitTest' ); Test::More::isa_ok( $trait_1, 'TraitTestBase' ); Test::More::isa_ok( $trait_2, 'TraitTest' ); Test::More::isa_ok( $trait_2, 'TraitTestBase' ); Test::More::ok( $trait_1->is("TPrintable"), '... trait 1 is TPrintable' ); Test::More::ok( $trait_1->is("TCompositeTest"), '... trait 1 is TCompositeTest' ); Test::More::ok( $trait_1->is("TComparable"), '... trait 1 is TComparable (because of TCompositeTest' ); Test::More::ok( $trait_2->is("TPrintable"), '... trait 2 is TPrintable' ); Test::More::ok( $trait_2->is("TCompositeTest"), '... trait 2 is TCompositeTest' ); Test::More::ok( $trait_2->is("TComparable"), '... trait 2 is TComparable (because of TCompositeTest' ); # check that it "can" execute the methods # that it should have gotten from the traits foreach my $method ( qw/ compositeTestRequirement compositeTest /, # from CompositeTest qw/ toString stringValue /, # from TPrintable qw/ compare equalTo notEqualTo /, # from TComparable ) { Test::More::can_ok( $trait_1, $method ); Test::More::can_ok( $trait_2, $method ); } # test the aliased method strVal Test::More::can_ok( $trait_1, 'strVal' ); Test::More::can_ok( $trait_2, 'strVal' ); # check overloads as well.... # for TComparable Test::More::ok( overload::Method( $trait_1, '==' ), '... trait 1 overload ==' ); Test::More::ok( overload::Method( $trait_1, '!=' ), '... trait 1 overload !=' ); Test::More::ok( overload::Method( $trait_1, '<=>' ), '... trait 1 overload <=>' ); # for TPrintable Test::More::ok( overload::Method( $trait_1, '""' ), '... trait 1 overload ""' ); # for TComparable Test::More::ok( overload::Method( $trait_2, '==' ), '... trait 2 overload ==' ); Test::More::ok( overload::Method( $trait_2, '!=' ), '... trait 2 overload !=' ); Test::More::ok( overload::Method( $trait_2, '<=>' ), '... trait 2 overload <=>' ); # for TPrintable Test::More::ok( overload::Method( $trait_2, '""' ), '... trait 2 overload ""' ); # now check if they behave as we expect # check "" operator from TPrintable Test::More::is( "$trait_1", '3.000 (overridden stringification)', '... and it should be stringified correctly' ); Test::More::is( "$trait_2", '3.000 (overridden stringification)', '... and it should be stringified correctly' ); # check == operator from TComparable # XXX using cmp_ok generates correct, but irrelevent "not numeric" warnings Test::More::ok( $trait_1 == $trait_2, '... and they should be equal' ); # check != operator from TComparable Test::More::ok( !( $trait_1 != $trait_2 ), '... and they shouldnt be not equal' ); # check the compare <=> operator Test::More::cmp_ok( ( $trait_1 <=> $trait_2 ), '==', 0, '... and they shouldnt be equal and therefore <=> return 0' ); # check the aliased stringValue function Test::More::like( $trait_1->strVal, qr/TraitTest=HASH\(0x[a-fA-F0-9]+\)/, '... and should return a reasonable strVal' ); Test::More::like( $trait_2->strVal, qr/TraitTest=HASH\(0x[a-fA-F0-9]+\)/, '... and should return a reasonable strVal' ); # now lets extract the actul trait and examine it my $trait; { no strict 'refs'; # get the trait out $trait = ${"TraitTest::TRAITS"}; } # check to see it is what we want it to be Test::More::isa_ok( $trait, 'Class::Trait::Config' ); # now examine the trait itself Test::More::is( $trait->name, 'COMPOSITE', '... get the traits name' ); Test::More::ok( Test::More::eq_array( $trait->sub_traits, [ 'TCompositeTest', 'TPrintable' ] ), '... this should not be empty' ); Test::More::ok( Test::More::eq_hash( $trait->conflicts, {} ), '... this should be empty' ); Test::More::ok( Test::More::eq_hash( $trait->requirements, { compare => 1, compositeTestRequirement => 1, toString => 2 # this was required twice } ), '... this should not be empty' ); Test::More::ok( Test::More::eq_hash( $trait->overloads, { '<=>' => 'compare', '==' => 'equalTo', '""' => 'toString', '!=' => 'notEqualTo' } ), '... this should not be empty' ); Test::More::ok( Test::More::eq_set( [ keys %{ $trait->methods } ], [ 'stringValue', 'compositeTest', 'strVal', 'equalTo', 'notEqualTo', 'isSameTypeAs', 'isExactly' ] ), '... this should not be empty' ); 110_trait_performs.t000444000765000765 303511320064413 17004 0ustar00ovidovid000000000000Class-Trait-0.31/t#!/usr/bin/perl use strict; use warnings; use Test::More tests => 21; BEGIN { unshift @INC => ( 't/test_lib', '/test_lib' ); } { package TestIt; use Class::Trait qw/RenameDoesToPerforms/; sub new { bless {}, shift } package TestItChild; our @ISA = 'TestIt'; } can_ok 'TestIt', 'new'; ok my $test = TestIt->new, '... and calling it should succeed'; isa_ok $test, 'TestIt', '... and the object it returns'; can_ok $test, 'reverse'; is $test->reverse('this'), 'siht', '... and methods should work correctly'; can_ok $test, 'performs'; ok $test->performs('RenameDoesToPerforms'), '... and it should return true for traits it can do'; ok !$test->performs('NoSuchTrait'), '... and it should return false for traits it cannot do'; ok !$test->can('does'), '... and it should not have a "does()" method'; ok !$test->can('is'), '... or an "is()" method'; can_ok 'TestItChild', 'new'; ok my $child = TestItChild->new, '... and calling it should succeed'; isa_ok $child, 'TestItChild', '... and the object it returns'; isa_ok $child, 'TestIt', '... and the object it returns'; can_ok $child, 'reverse'; is $child->reverse('this'), 'siht', '... and methods should work correctly'; can_ok $child, 'performs'; ok $child->performs('RenameDoesToPerforms'), '... and it should return true for traits it can do'; ok !$child->performs('NoSuchTrait'), '... and it should return false for traits it cannot do'; ok !$child->can('does'), '... and it should not have a "does()" method'; ok !$child->can('is'), '... or an "is()" method'; 120_trait_errors.t000444000765000765 1431211320064414 16505 0ustar00ovidovid000000000000Class-Trait-0.31/t#!/usr/bin/perl use strict; use warnings; use Test::More tests => 33; sub clean_inc { my @packages = qw( Circle Class::Trait Class::Trait::Base Class::Trait::Config Extra::TSpouse Polygamy TBomb TDisallowed TSpouse TestTraits ); foreach my $package (@packages) { no strict 'refs'; foreach my $glob ( keys %{"${package}::"} ) { undef *{"${package}::$glob"}; } } my @includes = map { s{::}{/}g; "$_.pm" } @packages; delete @INC{@includes}; } local $SIG{__WARN__} = sub { my $message = shift; return if $message =~ /Too late to run INIT block/; warn $message; }; BEGIN { chdir 't' if -d 't'; unshift @INC => ( '../lib', 'test_lib' ); } # # Note that Class::Trait->initialize is only being called because the code is # eval'ed and the INIT phase does not run. This is also necessary when # running under mod_perl # # # TSpouse: fuse explode # TBomb: fuse explode # eval <<'END_PACKAGE'; package TestTraits; use Class::Trait ( 'TSpouse', 'TBomb' ); Class::Trait->initialize; END_PACKAGE ok my $error = $@, 'Trying to load conflicting traits should fail'; like $error, qr/\QPackage TestTraits has conflicting methods (explode fuse)/, '... with an appropriate error message'; # # TSpouse: explode # TBomb: fuse explode # clean_inc(); eval <<'END_PACKAGE'; package TestTraits; use Class::Trait ( 'TSpouse' => { exclude => ['fuse'] }, 'TBomb' ); Class::Trait->initialize; END_PACKAGE ok $error = $@, 'Trying to load conflicting traits should fail'; like $error, qr/\QPackage TestTraits has conflicting methods (explode)/, '... with an appropriate error message'; # # TSpouse: explode # TBomb: fuse # clean_inc(); eval <<'END_PACKAGE'; package TestTraits; use Class::Trait ( 'TSpouse' => { exclude => ['fuse'] }, 'TBomb' => { exclude => ['explode'] }, ); Class::Trait->initialize; END_PACKAGE ok !$@, 'Trying to load properly configured traits should not fail'; can_ok 'TestTraits', 'fuse'; is TestTraits->fuse, 'Bomb fuse', '... and it should pull in the correct fuse() method'; can_ok 'TestTraits', 'explode'; is TestTraits->explode, 'Spouse explodes', '... and it should pull in the correct explode() method'; clean_inc(); eval <<'END_PACKAGE'; package TestTraits; use Class::Trait ( 'TSpouse' => { exclude => 'explode' } ); Class::Trait->initialize; sub explode { 'TestTraits explode' } END_PACKAGE ok !$@, 'Trying to load properly configured traits should not fail'; can_ok 'TestTraits', 'fuse'; is TestTraits->fuse, 'Spouse fuse', '... and it should pull in the correct fuse() method'; can_ok 'TestTraits', 'explode'; is TestTraits->explode, 'TestTraits explode', '... and it should not pull in explicitly defined methods'; # # Extra::TSpouse: fuse explode [ requires lawyer() ] # does: Original::TSpouse: fuse explode [ requires alimony() ] # clean_inc(); eval <<'END_PACKAGE'; package Polygamy; use Class::Trait 'Extra::TSpouse'; Class::Trait->initialize; sub alimony {} END_PACKAGE ok $@, 'Trying to load a trait which does not meet requirements should fail'; like $@, qr/\QRequirement (lawyer) for Extra::TSpouse not in Polygamy\E/, '... with an appropriate error message'; # # Extra::TSpouse: fuse explode [ requires lawyer() ] # does: Original::TSpouse: fuse explode [ requires alimony() ] # clean_inc(); eval <<'END_PACKAGE'; package Polygamy; use Class::Trait 'Extra::TSpouse'; Class::Trait->initialize; sub lawyer {} END_PACKAGE ok $@, 'Trying to load a trait which does not meet requirements should fail'; like $@, qr/\QRequirement (alimony) for Extra::TSpouse not in Polygamy\E/, '... and @REQUIREMENTS should bubble up correctly'; clean_inc(); # # Extra::TSpouse: fuse explode [requires lawyer()] # does: TSpouse: fuse explode # clean_inc(); eval <<'END_PACKAGE'; package Polygamy; use Class::Trait 'Extra::TSpouse'; Class::Trait->initialize; sub lawyer {} sub alimony {} END_PACKAGE ok !$@, 'Trying to load a trait which overrides an included traits methods should succeed'; can_ok Polygamy => 'explode'; is Polygamy->explode, 'Extra spouse explodes', '... and we should have the correct method'; can_ok Polygamy => 'fuse'; is Polygamy->fuse, 'Spouse fuse', '... and we should get the composed trait method'; clean_inc(); eval <<'END_PACKAGE'; package TestTraits; use Class::Trait ( 'TSpouse' => { exclude => ['fuse'] }, 'TBomb' => { exclude => ['explode'] }, ); Class::Trait->rename_does('%%'); Class::Trait->initialize; END_PACKAGE ok $@, 'Trying to rename does() to an illegal method name should fail'; like $@, qr/\QIllegal name for trait relation method (%%)/, '... telling us that it\'s an illegal method name'; clean_inc(); eval <<'END_PACKAGE'; package TestTraits; use Class::Trait 'Circle'; Class::Trait->initialize; END_PACKAGE ok $@, 'Trying to use a non-trait as a trait should fail'; like $@, qr/\QCircle is not a proper trait (inherits from Class::Trait::Base)\E/, '... telling us that it\'s not a trait'; clean_inc(); eval <<'END_PACKAGE'; package TestTraits; use Class::Trait 'TDisallowed'; Class::Trait->initialize; END_PACKAGE ok $@, 'Trying to use a trait with a disallowed method should fail'; like $@, qr/\QTrait TDisallowed attempted to implement disallowed method DESTROY\E/, '... telling us what the disallowed method is'; clean_inc(); eval <<'END_PACKAGE'; package TestTraits; use Class::Trait ( 'TSpouse' => { exclude => ['fuse', 'no_such_method' ] }, 'TBomb' => { exclude => ['explode'] }, ); Class::Trait->initialize; END_PACKAGE ok $@, 'Attempting to exclude a non-existent method should fail'; like $@, qr/\QAttempt to exclude method (no_such_method) that is not in trait (TSpouse)\E/, '... telling us which non-existent method we tried to exclude'; clean_inc(); eval <<'END_PACKAGE'; package TestTraits; use Class::Trait ( 'TSpouse' => { alias => { no_such_method => 'fuse' } }, 'TBomb' => { exclude => ['explode'] }, ); Class::Trait->initialize; END_PACKAGE ok $@, 'Attempting to alias a non-existent method should fail'; like $@, qr/\QAttempt to alias method (no_such_method) that is not in trait (TSpouse)\E/, '... telling us which non-existent method we tried to alias'; 130_trait_runtime_instance.t000444000765000765 1065511320064414 20547 0ustar00ovidovid000000000000Class-Trait-0.31/t#!/usr/bin/perl use strict; use warnings; no warnings 'redefine'; use Test::More tests => 43; #use Test::More qw/no_plan/; local $SIG{__WARN__} = sub { my $message = shift; return if $message =~ /Too late to run INIT block/; warn $message; }; BEGIN { chdir 't' if -d 't'; unshift @INC => ( '../lib', 'test_lib' ); } use Class::Trait; { package Foo; sub new { bless {}, shift } sub name { 'Foo' } sub explode { 'Foo explodes' } } my $foo = Foo->new; # # appling simple runtime traits to instances # require TSpouse; can_ok 'TSpouse', 'apply'; ok +TSpouse->apply($foo), '... and applying the trait to an instance should succeed'; ok $foo->isa('Foo'), '... and the instance should still respect "isa"'; cmp_ok ref $foo, 'ne', 'Foo', '... but it should be blessed into a new class'; ok $foo->does('TSpouse'), '... and it should be able to do the new trait'; can_ok $foo, 'name'; is $foo->name, 'Foo', '... original methods should still be available'; can_ok $foo, 'explode'; is $foo->explode, 'Spouse explodes', '... but corresponding trait methods should override them'; can_ok $foo, 'fuse'; is $foo->fuse, 'Spouse fuse', '... and the new trait methods should be available'; my $foo2 = Foo->new; is $foo2->explode, 'Foo explodes', 'Different instances of classes should not share runtime traits'; # # conflicting runtime traits to instances # can_ok 'Class::Trait', 'apply'; eval { Class::Trait->apply( $foo2, 'TSpouse', 'TBomb' ) }; ok $@, 'Trying to apply conflicting traits at runtime should fail'; like $@, qr/Package (?:\w|::)+ has conflicting methods \(.*\)/, '... with an appropriate error message'; undef $foo2; # make sure we don't reuse it # let's resolve those conflicts $foo = Foo->new; Class::Trait->apply( $foo, TSpouse => { exclude => 'fuse' }, TBomb => { exclude => 'explode' }, ); ok $foo->does('TSpouse'), '... and it should be able to do the first trait'; ok $foo->does('TBomb'), '... and it should be able to do the second trait'; can_ok $foo, 'name'; is $foo->name, 'Foo', '... original methods should still be available'; can_ok $foo, 'explode'; is $foo->explode, 'Spouse explodes', '... but corresponding trait methods should override them'; can_ok $foo, 'fuse'; is $foo->fuse, 'Bomb fuse', '... and the new trait methods should be available'; $foo2 = Foo->new; eval { Class::Trait->apply( $foo2, 'TSpouse' ) }; ok !$@, 'We should be able to apply the conflicting traits to separate instances'; # # let's apply the traits separately # $foo = Foo->new; Class::Trait->apply( $foo, 'TSpouse' ); ok !$foo->does('TBomb'), 'Trait information should not persist innappropriately'; Class::Trait->apply( $foo, 'TBomb' ); ok $foo->does('TBomb'), '... but we should have that info when it is available'; ok $foo->does('TSpouse'), '... and it should still report the other traits it can do'; can_ok $foo, 'name'; is $foo->name, 'Foo', '... original methods should still be available'; can_ok $foo, 'explode'; is $foo->explode, 'Bomb explodes', '... but later trait methods should override earlier ones'; can_ok $foo, 'fuse'; is $foo->fuse, 'Bomb fuse', '... and the new trait methods should be available'; my @does = sort $foo->does; is_deeply \@does, [qw/TBomb TSpouse/], '... and it should be able to report all traits it can do'; # # let's apply runtime composite traits with requirements # my $anon_package = ref $foo; require Extra::TSpouse; eval { Extra::TSpouse->apply($foo) }; ok $@, 'Trying to apply a runtime trait with unmet requirements should fail'; like $@, qr/Requirement \(alimony\) for Extra::TSpouse not in Foo::/, '... with an appropriate error message'; ok $foo->isa($anon_package), '... and the package of the object should not change'; { no warnings 'once'; *Foo::alimony = sub { 'Foo alimony' }; } eval { Extra::TSpouse->apply($foo) }; ok $@, 'Trying to apply a runtime trait with unmet requirements should fail'; like $@, qr/Requirement \(lawyer\) for Extra::TSpouse not in Foo::/, '... with an appropriate error message'; ok $foo->isa($anon_package), '... and the package of the object should not change'; { no warnings 'once'; *Foo::lawyer = sub { 'Foo lawyer' }; } ok +Extra::TSpouse->apply($foo), 'Satisfying all requirements of runtime traits should succeed'; isnt ref $foo, $anon_package, '... and the instance should have a new anonymous package'; is $foo->explode, 'Extra spouse explodes', '... and the correct method should be overridden'; 140_trait_runtime_class.t000444000765000765 1126211320064413 20043 0ustar00ovidovid000000000000Class-Trait-0.31/t#!/usr/bin/perl use strict; use warnings; no warnings 'redefine'; #use Test::More tests => 33; use Test::More qw/no_plan/; use Class::Trait; sub clean_inc { my @packages = qw( Circle Extra::TSpouse Foo Polygamy TBomb TDisallowed TSpouse TestTraits ); foreach my $package (@packages) { no strict 'refs'; clean_package( $package, keys %{"${package}::"} ); } my @includes = map { s{::}{/}g; "$_.pm" } @packages; delete @INC{@includes}; eval <<' END_FOO'; package Foo; sub new { bless {}, shift } sub name { 'Foo' } sub explode { 'Foo explodes' } } END_FOO } sub clean_package { my ( $package, @globs ) = @_; no strict 'refs'; foreach my $glob (@globs) { undef *{"${package}::$glob"}; } Class::Trait::_clear_all_caches(); Class::Trait::_clear_does_cache(); # internal testing hook no warnings 'once'; undef $Foo::TRAITS; } local $SIG{__WARN__} = sub { my $message = shift; return if $message =~ /Too late to run INIT block/; warn $message; }; BEGIN { chdir 't' if -d 't'; unshift @INC => ( '../lib', 'test_lib' ); } # # appling simple runtime traits to instances # clean_inc(); Class::Trait->apply(Foo => 'TSpouse'); my $foo = Foo->new; isa_ok $foo, 'Foo', '... and the object it returns'; can_ok 'Foo', 'does'; ok +Foo->does('TSpouse'), '... and it should be able to do the new trait'; can_ok $foo, 'name'; is $foo->name, 'Foo', '... original methods should still be available'; can_ok $foo, 'explode'; is $foo->explode, 'Spouse explodes', '... but corresponding trait methods should override them'; can_ok $foo, 'fuse'; is $foo->fuse, 'Spouse fuse', '... and the new trait methods should be available'; my $foo2 = Foo->new; is $foo2->explode, 'Spouse explodes', 'Different instances of classes should share runtime traits applied to classes'; # # conflicting runtime traits to instances # clean_inc(); can_ok 'Class::Trait', 'apply'; eval { Class::Trait->apply( 'Foo', 'TSpouse', 'TBomb' ) }; ok $@, 'Trying to apply conflicting traits at runtime should fail'; like $@, qr/Package (?:\w|::)+ has conflicting methods \(.*\)/, '... with an appropriate error message'; # let's resolve those conflicts clean_inc(); Class::Trait->apply( 'Foo', TSpouse => { exclude => 'fuse' }, TBomb => { exclude => 'explode' }, ); $foo = Foo->new; ok $foo->does('TSpouse'), '... and it should be able to do the first trait'; ok $foo->does('TBomb'), '... and it should be able to do the second trait'; can_ok $foo, 'name'; is $foo->name, 'Foo', '... original methods should still be available'; can_ok $foo, 'explode'; is $foo->explode, 'Spouse explodes', '... but corresponding trait methods should override them'; can_ok $foo, 'fuse'; is $foo->fuse, 'Bomb fuse', '... and the new trait methods should be available'; # # let's apply the traits separately # clean_inc(); Class::Trait->apply( Foo => 'TSpouse' ); $foo = Foo->new; ok !$foo->does('TBomb'), 'Trait information should not persist innappropriately'; Class::Trait->apply( Foo => 'TBomb' ); ok $foo->does('TBomb'), '... but we should have that info when it is available'; ok $foo->does('TSpouse'), '... and it should still report the other traits it can do'; can_ok $foo, 'name'; is $foo->name, 'Foo', '... original methods should still be available'; can_ok $foo, 'explode'; is $foo->explode, 'Bomb explodes', '... but later trait methods should override earlier ones'; can_ok $foo, 'fuse'; is $foo->fuse, 'Bomb fuse', '... and the new trait methods should be available'; my @does = sort $foo->does; is_deeply \@does, [qw/TBomb TSpouse/], '... and it should be able to report all traits it can do'; # # let's apply runtime composite traits with requirements # clean_inc(); eval { Class::Trait->apply(Foo => 'Extra::TSpouse') }; ok $@, 'Trying to apply a runtime trait with unmet requirements should fail'; like $@, qr/Requirement \(alimony\) for Extra::TSpouse not in Foo/, '... with an appropriate error message'; clean_inc(); { no warnings 'once'; *Foo::alimony = sub { 'Foo alimony' }; } eval { Class::Trait->apply(Foo => 'Extra::TSpouse') }; ok $@, 'Trying to apply a runtime trait with unmet requirements should fail'; like $@, qr/Requirement \(lawyer\) for Extra::TSpouse not in Foo/, '... with an appropriate error message'; clean_inc(); { no warnings 'once'; *Foo::alimony = sub { 'Foo alimony' }; *Foo::lawyer = sub { 'Foo lawyer' }; } ok +Class::Trait->apply(Foo => 'Extra::TSpouse'), 'Satisfying all requirements of runtime traits should succeed'; is $foo->explode, 'Extra spouse explodes', '... and the correct method should be overridden'; 150_inherited_does.t000444000765000765 54211320064414 16716 0ustar00ovidovid000000000000Class-Trait-0.31/t#!/usr/bin/perl use strict; use warnings; use Test::More tests => 2; BEGIN { unshift @INC => ( 't/test_lib', '/test_lib' ); } { package P1; use Class::Trait qw(TBomb); } { package P2; use base qw(P1); } ok +P1->does('TBomb'), 'Traits should do what traits should do'; ok +P2->does('TBomb'), '... and so should their subclasses'; pod.t000444000765000765 25711320064414 14131 0ustar00ovidovid000000000000Class-Trait-0.31/t#!/usr/bin/perl use strict; use warnings; use Test::More; eval "use Test::Pod 1.14"; plan skip_all => "Test::Pod 1.14 required for testing POD" if $@; all_pod_files_ok(); pod_coverage.t000444000765000765 136111320064413 16020 0ustar00ovidovid000000000000Class-Trait-0.31/t#!/usr/bin/perl use strict; use warnings; use Test::More; local $SIG{__WARN__} = sub { my $message = shift; return if $message =~ /Too late to run INIT block/; warn $message; }; eval "use Test::Pod::Coverage"; plan skip_all => "Test::Pod::Coverage required for testing POD coverage" if $@; # dont bother testing Class::Trait itself as none of the methods are really # public and all interaction is done through the 'import' interface anyway. plan tests => 6; pod_coverage_ok('Class::Trait::Config'); pod_coverage_ok('Class::Trait::Base'); pod_coverage_ok('Class::Trait::Reflection'); pod_coverage_ok('Class::Trait::Lib::TEquality'); pod_coverage_ok('Class::Trait::Lib::TPrintable'); pod_coverage_ok('Class::Trait::Lib::TComparable'); Test000755000765000765 011320064414 13760 5ustar00ovidovid000000000000Class-Trait-0.31/tLoadingTraitsWithColonsInThem.pm000444000765000765 22211320064414 22312 0ustar00ovidovid000000000000Class-Trait-0.31/t/Test package Test::LoadingTraitsWithColonsInThem; use strict; use warnings; use Class::Trait 'base'; sub isLoaded { return __PACKAGE__; } 1; Another000755000765000765 011320064414 15360 5ustar00ovidovid000000000000Class-Trait-0.31/t/TestColonInTheName.pm000444000765000765 21411320064414 20633 0ustar00ovidovid000000000000Class-Trait-0.31/t/Test/Another package Test::Another::ColonInTheName; use strict; use warnings; use Class::Trait 'base'; sub isLoaded { return __PACKAGE__; } 1; test_lib000755000765000765 011320064414 14646 5ustar00ovidovid000000000000Class-Trait-0.31/tBasicTrait.pm000444000765000765 12511320064414 17344 0ustar00ovidovid000000000000Class-Trait-0.31/t/test_libpackage BasicTrait; use strict; use warnings; use Class::Trait 'TSimple'; 1; BasicTraitImport.pm000444000765000765 13311320064414 20536 0ustar00ovidovid000000000000Class-Trait-0.31/t/test_libpackage BasicTraitImport; use strict; use warnings; use Class::Trait 'TImport'; 1; Circle.pm000444000765000765 75011320064414 16524 0ustar00ovidovid000000000000Class-Trait-0.31/t/test_lib use strict; use warnings; package Circle; use overload ( '==' => \&equalTo ); use Class::Trait "TCircle" => { exclude => 'equalTo' }, "TColor" => { exclude => 'equalTo' }; sub new { return bless { name => "Circle" } => "Circle"; } sub getCenter { } sub getRadius { } sub setRadius { } sub setCenter { } sub getRGB { } sub setRGB { } sub equalTo { my ( $self, $right ) = @_; $self->isSameTypeAs($right); return $self->{name} eq $right->{name}; } 1; __DATA__ Employee.pm000444000765000765 11711320064414 17077 0ustar00ovidovid000000000000Class-Trait-0.31/t/test_libpackage Employee; use strict; use warnings; use base qw(PersonWithTitle); 1; FooExport.pm000444000765000765 22211320064414 17242 0ustar00ovidovid000000000000Class-Trait-0.31/t/test_libpackage FooExport; use strict; use warnings; use base 'Exporter'; our @EXPORT_OK = qw/this that/; sub this { 'this' } sub that { 'that' } 1; Person.pm000444000765000765 16111320064414 16565 0ustar00ovidovid000000000000Class-Trait-0.31/t/test_libpackage Person; use strict; use warnings; sub name { 'George Richardson' } sub new { bless({}, shift()) } 1; PersonWithTitle.pm000444000765000765 15211320064414 20423 0ustar00ovidovid000000000000Class-Trait-0.31/t/test_libpackage PersonWithTitle; use strict; use warnings; use base qw(Person); use Class::Trait qw(Ttitle); 1; Read.pm000444000765000765 40711320064414 16175 0ustar00ovidovid000000000000Class-Trait-0.31/t/test_libpackage Read; use strict; use warnings; sub new { my ($_class) = @_; my $class = ref($_class) || $_class; my $reader = {}; bless($reader, $class); return $reader; } sub read { my ($self) = @_; return "value read from Read::read method"; } 1; __DATA__ RenameDoesToPerforms.pm000444000765000765 27311320064413 21365 0ustar00ovidovid000000000000Class-Trait-0.31/t/test_libpackage RenameDoesToPerforms; use strict; use warnings; use Class::Trait qw/base performs/; sub reverse { my ($proto, $message) = @_; return scalar reverse $message; } 1; SyncRead.pm000444000765000765 16011320064413 17025 0ustar00ovidovid000000000000Class-Trait-0.31/t/test_libpackage SyncRead; use strict; use warnings; use base ("Read"); use Class::Trait ("TSyncRead"); 1; __DATA__ TBomb.pm000444000765000765 21511320064414 16322 0ustar00ovidovid000000000000Class-Trait-0.31/t/test_libpackage TBomb; use strict; use warnings; use Class::Trait 'base'; sub explode { "Bomb explodes"; } sub fuse { "Bomb fuse"; } 1; TCircle.pm000444000765000765 47511320064414 16654 0ustar00ovidovid000000000000Class-Trait-0.31/t/test_lib use strict; use warnings; package TCircle; use Class::Trait 'base'; use Class::Trait qw(TMagnitude TGeometry); our %OVERLOADS = ( '<' => "lessThan", '==' => "equalTo" ); sub lessThan { my ( $left, $right ) = @_; # ... } sub equalTo { my ( $left, $right ) = @_; # ... } 1; __DATA__ TColor.pm000444000765000765 203011320064414 16536 0ustar00ovidovid000000000000Class-Trait-0.31/t/test_lib use strict; use warnings; package TColor; use Class::Trait 'base'; use Class::Trait "TEquality"; our @REQUIRES = qw(getRGB setRGB); sub getRed { my ($self) = @_; my ($red) = $self->getRGB(); return $red; } sub setRed { my ( $self, $red ) = @_; $self->setRGB( $red, undef, undef ); } sub getGreen { my ($self) = @_; my ( undef, $green ) = $self->getRGB(); return $green; } sub setGreen { my ( $self, $green ) = @_; $self->setRGB( undef, $green, undef ); } sub getBlue { my ($self) = @_; my ( undef, undef, $blue ) = $self->getRGB(); return $blue; } sub setBlue { my ( $self, $blue ) = @_; $self->setRGB( undef, undef, $blue ); } sub equalTo { my ( $left, $right ) = @_; ( $left->isSameTypeAs($right) ) || die "cannot compare non-color objects"; my @left = $left->getRGB(); foreach my $i ( $right->getRGB() ) { if ( $i != shift @left ) { # return false return 0; } } # return true return 1; } 1; __DATA__ TCompositeTest.pm000444000765000765 41311320064414 20245 0ustar00ovidovid000000000000Class-Trait-0.31/t/test_libpackage TCompositeTest; use strict; use warnings; use Class::Trait 'base'; use Class::Trait qw(TPrintable TComparable); our @REQUIRES = ("compositeTestRequirement"); sub compositeTest { my ($self) = @_; $self->compositeTestRequirement(); } 1; __DATA__ TDisallowed.pm000444000765000765 13611320064413 17533 0ustar00ovidovid000000000000Class-Trait-0.31/t/test_libpackage TDisallowed; use strict; use warnings; use Class::Trait 'base'; sub DESTROY {} 1; TGeometry.pm000444000765000765 55611320064413 17245 0ustar00ovidovid000000000000Class-Trait-0.31/t/test_lib use strict; use warnings; package TGeometry; use Class::Trait 'base'; our @REQUIRES = qw( getCenter setCenter getRadius setRadius ); sub area { my ($self) = @_; # ... } sub bounds { my ($self) = @_; # ... } sub diameter { my ($self) = @_; # ... } sub scaleBy { my ( $self, $magnitude ) = @_; # ... } 1; __DATA__ TImport.pm000444000765000765 21611320064414 16716 0ustar00ovidovid000000000000Class-Trait-0.31/t/test_libpackage TImport; use strict; use warnings; use FooExport qw(this that); use Class::Trait 'base'; sub getName { return "TImport"; } 1; TMagnitude.pm000444000765000765 143511320064414 17405 0ustar00ovidovid000000000000Class-Trait-0.31/t/test_lib use strict; use warnings; package TMagnitude; use Class::Trait 'base'; use Class::Trait ("TEquality"); our %OVERLOADS = ( '<' => "lessThan", '<=' => "lessThanOrEqualTo", '>' => "greaterThan", '>=' => "greaterThanOrEqualTo", ); our @REQUIRES = qw( lessThan equalTo ); sub lessThanOrEqualTo { my ( $left, $right ) = @_; return ( $left->lessThan($right) || $left->equalTo($right) ); } sub greaterThan { my ( $left, $right ) = @_; return ( $right->isLessThan($left) ); } sub greaterThanOrEqualTo { my ( $left, $right ) = @_; return ( $right->isLessThanOrEqualTo($left) ); } sub isBetween { my ( $self, $left, $right ) = @_; return ( $self->greaterThanOrEqualTo($left) && $self->lessThanOrEqualTo($right) ); } 1; __DATA__ TraitTest.pm000444000765000765 104011320064413 17256 0ustar00ovidovid000000000000Class-Trait-0.31/t/test_lib package TraitTest; use strict; use warnings; use base qw(TraitTestBase); use Class::Trait ( TCompositeTest => { alias => { stringValue => "strVal" }, exclude => [ "stringValue" ] }, "TPrintable" ); sub compare { my ($self, $right) = @_; return ($self->{value} <=> $right->{value}); } sub toString { my ($self) = @_; return sprintf("%.3f", $self->SUPER::toString()) . " (overridden stringification)"; } sub compositeTestRequirement { return "Composite Test Requirement" } 1; __DATA__ TraitTestBase.pm000444000765000765 65011320064414 20040 0ustar00ovidovid000000000000Class-Trait-0.31/t/test_libpackage TraitTestBase; use strict; use warnings; use Class::Trait "TPrintable"; use overload ( '==' => "_equals" ); sub new { my ($class, $value) = @_; my $test = { value => $value || 0 }; bless($test, $class); return $test; } sub _equals { my ($self, $value) = @_; return ($self->{value} == $value); } sub toString { my ($self) = @_; return $self->{value}; } 1; TSimple.pm000444000765000765 16111320064414 16674 0ustar00ovidovid000000000000Class-Trait-0.31/t/test_libpackage TSimple; use strict; use warnings; use Class::Trait 'base'; sub getName { return "TSimple"; } 1; TSpouse.pm000444000765000765 22311320064414 16720 0ustar00ovidovid000000000000Class-Trait-0.31/t/test_libpackage TSpouse; use strict; use warnings; use Class::Trait 'base'; sub explode { "Spouse explodes"; } sub fuse { "Spouse fuse"; } 1; TSyncRead.pm000444000765000765 43211320064414 17154 0ustar00ovidovid000000000000Class-Trait-0.31/t/test_lib package TSyncRead; use strict; use warnings; use Fcntl qw(:flock); use Class::Trait 'base'; our @REQUIRES = ("read"); sub read { my ($self) = @_; $self->lock(); my $value = $self->SUPER::read(); $self->unlock(); return $value; } sub lock { } sub unlock { } 1; __DATA__Ttitle.pm000444000765000765 27411320064414 16571 0ustar00ovidovid000000000000Class-Trait-0.31/t/test_libpackage Ttitle; use strict; use warnings; use Class::Trait qw(base); sub title { 'Mgr.' } sub name { my $this = shift; $this->title . ' '. $this->SUPER::name; } 1; Extra000755000765000765 011320064414 15731 5ustar00ovidovid000000000000Class-Trait-0.31/t/test_libTSpouse.pm000444000765000765 32511320064414 20006 0ustar00ovidovid000000000000Class-Trait-0.31/t/test_lib/Extrapackage Extra::TSpouse; use strict; use warnings; use Class::Trait 'base'; use Class::Trait 'Original::TSpouse'; # conflicts: explode our @REQUIRES = 'lawyer'; sub explode { "Extra spouse explodes"; } 1; Original000755000765000765 011320064414 16412 5ustar00ovidovid000000000000Class-Trait-0.31/t/test_libTSpouse.pm000444000765000765 27111320064414 20467 0ustar00ovidovid000000000000Class-Trait-0.31/t/test_lib/Originalpackage Original::TSpouse; use strict; use warnings; use Class::Trait 'base'; our @REQUIRES = 'alimony'; sub explode { "Spouse explodes"; } sub fuse { "Spouse fuse"; } 1;