Sub-Override-0.12/0000755000175000017500000000000014634302043012745 5ustar robinrobinSub-Override-0.12/Changes0000644000175000017500000000306414634067557014265 0ustar robinrobin0.12 Mon Jun 17 2024 - Add 'inject' method which can inject a new subroutine into a namespace. - Add 'inherit' method which can inherit a subroutine from a parent object. - Bug fix for wrap not restoring during destruction. - Internal cleanup. 0.11 Tue May 14 2024 - Update the 'wrap' routine so it handles prototypes transparently. - Update the 'wrap' routine to prevent creation of an extra stack frame. - Minor doc updates. 0.10 Wed Nov 22 2023 Add a 'wrap' routine that allows you to call the original sub. 0.09 Wed Jan 16 2013 Switch from Test::Exception to Test::Fatal. Fix two typos on the POD. Patches from Ansgar Burchardt and david.skyba. 0.08 Wed Sep 21 2005 Remembered to update Changes file. Grr. I really need a "lint" script which can check to see if I've forgotten stupid things. 0.07 Wed Sep 21 2005 Added dependency on Sub::Uplevel even though I don't use it. Tests keep failing for folks because of it. Added pod tests. Added "override" as a synonym for "replace". 0.06 Fri Dec 3 2003 - Ensure that restore() always restores the sub to its original state. This allows a subroutine to be safely overridden multiple times. 0.05 Tue Aug 24 2004 - Removed accidental dependency on Data::Dumper::Simple 0.04 Mon Aug 23 2004 - Fixed bug where explicitly restoring subs whose names were not fully qualified would fail. 0.01 Mon May 24 09:44:31 2004 - original version; created by h2xs 1.23 with options -AX -n Sub::Override Sub-Override-0.12/t/0000755000175000017500000000000014634302043013210 5ustar robinrobinSub-Override-0.12/t/override.t0000644000175000017500000001633214634067177015241 0ustar robinrobinuse strict; use warnings; use Test::More; use Test::Fatal; my $CLASS; { package Foo; sub bar { return 'original value'; } sub baz { return 'original baz value'; } } BEGIN { chdir 't' if -d 't'; use lib '../lib'; $CLASS = 'Sub::Override'; use_ok($CLASS) || die; } can_ok( $CLASS, 'new' ); my $override = $CLASS->new; isa_ok( $override, $CLASS, '... and the object it returns' ); can_ok( $override, 'replace' ); like exception { $override->replace( 'No::Such::Sub', '' ) }, qr/^\QCannot replace non-existent sub (No::Such::Sub)\E/, "... and we can't replace a sub which doesn't exist"; like exception { $override->replace( 'Foo::bar', 'not a subref' ) }, qr/\(not a subref\) must be a code reference/, '... and only a code reference may replace a subroutine'; ok( $override->replace( 'Foo::bar', sub {'new subroutine'} ), '... and replacing a subroutine should succeed' ); is( Foo::bar(), 'new subroutine', '... and the subroutine should exhibit the new behavior' ); ok( $override->replace( 'Foo::bar' => sub {'new subroutine 2'} ), '... and we should be able to replace a sub more than once' ); is( Foo::bar(), 'new subroutine 2', '... and still have the sub exhibit the new behavior' ); can_ok( $override, 'override' ); ok( $override->override( 'Foo::bar' => sub {'new subroutine 3'} ), '... and it should also replace a subroutine' ); is( Foo::bar(), 'new subroutine 3', '... and act just like replace()' ); can_ok( $override, 'restore' ); like exception { $override->restore('Did::Not::Override') }, qr/^\QCannot restore a sub that was not replaced (Did::Not::Override)/, '... and it should fail if the subroutine had not been replaced'; $override->restore('Foo::bar'); is( Foo::bar(), 'original value', '... and the subroutine should exhibit the original behavior' ); like exception { $override->restore('Foo::bar') }, qr/^\QCannot restore a sub that was not replaced (Foo::bar)/, '... but we should not be able to restore it twice'; { my $new_override = $CLASS->new; ok( $new_override->replace( 'Foo::bar', sub {'lexical value'} ), 'A new override object should be able to replace a subroutine' ); is( Foo::bar(), 'lexical value', '... and the subroutine should exhibit the new behavior' ); } is( Foo::bar(), 'original value', '... but should revert to the original behavior when the object falls out of scope' ); { my $new_override = $CLASS->new( 'Foo::bar', sub {'lexical value'} ); ok( $new_override, 'We should be able to override a sub from the constructor' ); is( Foo::bar(), 'lexical value', '... and the subroutine should exhibit the new behavior' ); ok( $new_override->restore, '... and we do not need an argument to restore if only one sub is overridden' ); is( Foo::bar(), 'original value', '... and the subroutine should exhibit its original behavior' ); $new_override->replace( 'Foo::bar', sub { } ); $new_override->replace( 'Foo::baz', sub { } ); like exception { $new_override->restore }, qr/You must provide the name of a sub to restore: \(Foo::bar, Foo::baz\)/, '... but we must explicitly provide the sub name if more than one was replaced'; } { package TempReplace; sub foo {23} sub bar {42} my $override = $CLASS->new( 'foo', sub {42} ); $override->replace( 'bar', sub {'barbar'} ); main::is( foo(), 42, 'Not fully qualifying a sub name will assume the current package' ); $override->restore('foo'); main::is( foo(), 23, '... and we should be able to restore said sub' ); $override->restore('TempReplace::bar'); main::is( bar(), 42, '... even if we use a full qualified sub name' ); } can_ok( $override, 'wrap' ); { package TempWrap; sub foo {23} sub bar ($$) {$_[0] + $_[1]} my $override = $CLASS->new; main::ok( $override->wrap( 'foo', sub { my ($orig, @args) = @_; return $args[0] ? 24 : $orig->(); } ), '... and we should be able to successfully wrap a subroutine' ); main::is( foo(), 23, '... and wrapped sub foo conditionally returns original value' ); main::is( foo(1), 24, '... and wrapped sub foo conditionally returns override value' ); $override->restore('foo'); main::is( foo(1), 23, '... and we can restore a wrapped subroutine' ); main::ok( $override->wrap( 'bar', sub { my ($orig, @args) = @_; return $args[0] == 4 && $args[1] == 2 ? 42 : $orig->(@args); } ), '... and we should be able to successfully wrap a prototyped subroutine' ); main::is( bar(5,2), 7, '... and wrapped prototyped sub bar conditionally returns original value' ); main::is( bar(4,2), 42, '... and wrapped prototyped sub bar conditionally returns override value' ); # make sure there are no left-over references preventing destroy from running. undef $override; main::is( bar(4,2), 6, '... and we can restore a wrapped subroutine' ); } can_ok( $override, 'inject' ); { package TempInject; sub foo { 23 } sub bar ($$) { $_[0] + $_[1] } my $override = $CLASS->new; main::like main::exception { $override->inject( 'foo', '' ) }, qr/\QCannot create a sub that already exists (TempInject::foo)/, '... and we should not be able to inject subs over existing subs'; main::ok( $override->inject( 'something', sub { 42 } ), '... but injecting a subroutine should succeed' ); main::is( TempInject::something(), 42, '... and we should be able to call the new function' ); $override->restore('something'); main::like main::exception { TempInject::something() }, qr/\QUndefined subroutine &TempInject::something called\E/, '... and we should be able to restore the original behavior'; } can_ok( $override, 'inherit' ); { package TempInheritParent; sub foo { 'foo' } sub bar { 'bar' } package TempInheritChild; our @ISA = qw(TempInheritParent); sub foo { 'foo' } sub baz { 'baz' } my $override = $CLASS->new; main::like main::exception { $override->inherit( 'foo', sub { 'foo-override'; } ) }, qr/\QCannot create a sub that already exists (TempInheritChild::foo)/, '... and we should not be able to inherit and existing inherited sub'; main::like main::exception { $override->inherit( 'baz', sub { 'baz-override'; } ) }, qr/\QCannot create a sub that already exists (TempInheritChild::baz)/, '... and we should not be able to inherit an existing sub'; main::like main::exception { $override->inherit( 'foobarbaz', sub { 'foo-override'; } ) }, qr/\QSub does not exist in parent class (TempInheritChild::foobarbaz)/, '... and we should not be able to inherit a non-existing sub'; main::ok( $override->inherit( 'bar', sub { 'bar-inherited' } ), '... but inheriting a subroutine should succeed' ); main::is( TempInheritChild->bar(), 'bar-inherited', '... and we should be able to call the new function' ); $override->restore('bar'); main::is( TempInheritChild->bar(), 'bar', '... and we should be able to restore the original behaviour' ); } done_testing; Sub-Override-0.12/xt/0000755000175000017500000000000014634302043013400 5ustar robinrobinSub-Override-0.12/xt/pod-coverage.t0000644000175000017500000000025514514544625016155 0ustar robinrobin#!perl -T use Test::More; eval "use Test::Pod::Coverage 1.04"; plan skip_all => "Test::Pod::Coverage 1.04 required for testing POD coverage" if $@; all_pod_coverage_ok(); Sub-Override-0.12/xt/pod.t0000644000175000017500000000021414514544625014357 0ustar robinrobin#!perl -T 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(); Sub-Override-0.12/lib/0000755000175000017500000000000014634302043013513 5ustar robinrobinSub-Override-0.12/lib/Sub/0000755000175000017500000000000014634302043014244 5ustar robinrobinSub-Override-0.12/lib/Sub/Override.pm0000644000175000017500000003356314634300570016376 0ustar robinrobinpackage Sub::Override; use strict; use warnings; use Carp qw(croak); use Scalar::Util qw(set_prototype); our $VERSION = '0.12'; sub new { my $class = shift; my $self = bless {}, $class; $self->replace(@_) if @_; return $self; } { no warnings 'once'; # because override() was a better name and this is what it should have been # called. *override = *replace{CODE}; } sub replace { my ( $self, $sub_to_replace, $new_sub ) = @_; $sub_to_replace = $self->_get_fully_qualified_sub_name($sub_to_replace); $self->_ensure_code_slot_exists($sub_to_replace)->_validate_sub_ref($new_sub); { no strict 'refs'; $self->{$sub_to_replace} ||= *$sub_to_replace{CODE}; no warnings 'redefine'; *$sub_to_replace = $new_sub; } return $self; } sub inject { my ( $self, $sub_to_inject, $new_sub ) = @_; $sub_to_inject = $self->_get_fully_qualified_sub_name($sub_to_inject); $self->_ensure_code_slot_does_not_exist($sub_to_inject)->_validate_sub_ref($new_sub); { no strict 'refs'; $self->{$sub_to_inject} = undef; no warnings 'redefine'; *$sub_to_inject = $new_sub; } return $self; } sub inherit { my ( $self, $sub_to_inherit, $new_sub ) = @_; $sub_to_inherit = $self->_get_fully_qualified_sub_name($sub_to_inherit); $self->_ensure_code_slot_exists_in_parent_class($sub_to_inherit)->_validate_sub_ref($new_sub); { no strict 'refs'; $self->{$sub_to_inherit} = undef; no warnings 'redefine'; *$sub_to_inherit = $new_sub; } return $self; } sub wrap { my ( $self, $sub_to_replace, $new_sub ) = @_; $sub_to_replace = $self->_get_fully_qualified_sub_name($sub_to_replace); $self->_ensure_code_slot_exists($sub_to_replace)->_validate_sub_ref($new_sub); { no strict 'refs'; $self->{$sub_to_replace} ||= *$sub_to_replace{CODE}; # passing $sub_to_replace directly to arguments prevents early destruction. my $weakened_sub_to_replace = $self->{$sub_to_replace}; my $code = sub { unshift(@_, $weakened_sub_to_replace); goto &$new_sub }; my $prototype = prototype($self->{$sub_to_replace}); set_prototype(\&$code, $prototype) if defined $prototype; no warnings 'redefine'; *$sub_to_replace = $code; } return $self; } sub restore { my ( $self, $name_of_sub ) = @_; $name_of_sub = $self->_get_fully_qualified_sub_name($name_of_sub); if ( !$name_of_sub && 1 == keys %$self ) { ($name_of_sub) = keys %$self; } croak( sprintf 'You must provide the name of a sub to restore: (%s)' => join ', ' => sort keys %$self ) unless $name_of_sub; croak("Cannot restore a sub that was not replaced ($name_of_sub)") unless exists $self->{$name_of_sub}; no strict 'refs'; no warnings 'redefine'; my $maybe_sub_ref = delete $self->{$name_of_sub}; if ( defined $maybe_sub_ref ) { *$name_of_sub = $maybe_sub_ref; } else { undef *$name_of_sub; } return $self; } sub DESTROY { my $self = shift; no strict 'refs'; # "misc" suppresses warning: 'Undefined value assigned to typeglob' no warnings 'redefine', 'misc'; while ( my ( $sub_name, $maybe_sub_ref ) = each %$self ) { if ( defined $maybe_sub_ref ) { *$sub_name = $maybe_sub_ref; } else { undef *$sub_name; } } } sub _get_fully_qualified_sub_name { my ( $self, $subname ) = @_; if ( ( $subname || '' ) =~ /^\w+$/ ) { # || "" for suppressing test warnings my $package = do { my $call_level = 0; my $this_package; while ( !$this_package || __PACKAGE__ eq $this_package ) { ($this_package) = caller($call_level); $call_level++; } $this_package; }; $subname = "${package}::$subname"; } return $subname; }; sub _validate_sub_ref { my ( $self, $sub_ref ) = @_; unless ( 'CODE' eq ref $sub_ref ) { croak("($sub_ref) must be a code reference"); } return $self; }; sub _ensure_code_slot_exists { my ( $self, $code_slot ) = @_; no strict 'refs'; unless ( defined *{$code_slot}{CODE} ) { croak("Cannot replace non-existent sub ($code_slot)"); } return $self; }; sub _ensure_code_slot_does_not_exist { my ( $self, $code_slot ) = @_; no strict 'refs'; if ( defined *{$code_slot}{CODE} ) { croak("Cannot create a sub that already exists ($code_slot)"); } return $self; }; sub _ensure_code_slot_exists_in_parent_class { my ( $self, $code_slot ) = @_; $self->_ensure_code_slot_does_not_exist($code_slot); { no strict 'refs'; my $class = *{$code_slot}{PACKAGE}; my $method = *{$code_slot}{NAME}; croak("Sub does not exist in parent class ($code_slot)") unless $class->can($method); } return $self; }; 1; __END__ =head1 NAME Sub::Override - Perl extension for easily overriding subroutines =head1 VERSION 0.12 =head1 SYNOPSIS use Sub::Override; sub foo { 'original sub' }; print foo(); # prints 'original sub' my $override = Sub::Override->new( foo => sub { 'overridden sub' } ); print foo(); # prints 'overridden sub' $override->restore; print foo(); # prints 'original sub' =head1 DESCRIPTION =head2 The Problem Sometimes subroutines need to be overridden. In fact, your author does this frequently for tests. Particularly when testing, using a Mock Object can be overkill when all you want to do is override one tiny, little function. Overriding a subroutine is often done with syntax similar to the following. { local *Some::sub = sub {'some behavior'}; # do something } # original subroutine behavior restored This has a few problems. { local *Get::some_feild = { 'some behavior' }; # do something } In the above example, not only have we probably misspelled the subroutine name, but even if there had been a subroutine with that name, we haven't overridden it. These two bugs can be subtle to detect. Further, if we're attempting to localize the effect by placing this code in a block, the entire construct is cumbersome. Hook::LexWrap also allows us to override sub behavior, but I can never remember the exact syntax. =head2 An easier way to replace subroutines Instead, C allows the programmer to simply name the sub to replace and to supply a sub to replace it with. my $override = Sub::Override->new('Some::sub', sub {'new data'}); # which is equivalent to: my $override = Sub::Override->new; $override->replace('Some::sub', sub { 'new data' }); You can replace multiple subroutines, if needed: $override->replace('Some::sub1', sub { 'new data1' }); $override->replace('Some::sub2', sub { 'new data2' }); $override->replace('Some::sub3', sub { 'new data3' }); If replacing the subroutine succeeds, the object is returned. This allows the programmer to chain the calls, if this style of programming is preferred: $override->replace('Some::sub1', sub { 'new data1' }) ->replace('Some::sub2', sub { 'new data2' }) ->replace('Some::sub3', sub { 'new data3' }); If the subroutine has a prototype, the new subroutine should be declared with same prototype as original one: $override->replace('Some::sub_with_proto', sub ($$) { ($_[0], $_ [1]) }); A subroutine may be replaced as many times as desired. This is most useful when testing how code behaves with multiple conditions. $override->replace('Some::thing', sub { 0 }); is($object->foo, 'wibble', 'wibble is returned if Some::thing is false'); $override->replace('Some::thing', sub { 1 }); is($object->foo, 'puppies', 'puppies are returned if Some::thing is true'); =head2 Injecting a subroutine If you want to inject a subroutine into a package, you can use the C method. This is identical to C, except that it requires that the subroutine does not exist: $override->inject('Some::sub', sub {'new data'}); This is useful if you want to add a subroutine to a package that doesn't already have it. If you attempt to inject a subroutine that already exists, an exception will be thrown. $override->inject('Some::sub', sub {'new data'}); # works $override->inject('Some::sub', sub {'new data'}); # throws an exception Calling C or allowing the C<$override> to go out of scope will remove the injected subroutine. $override->inject('Some::sub', sub {'new data'}); $override->restore('Some::sub'); # removes the injected subroutine =head2 Inheriting a subroutine Similar to 'inject', 'inherit' will only allow you to create a new subroutine on a child object that inherits the routine from the parent, and doesn't exist in the child: package Parent; sub foo {} sub bar {} package Child; use parent 'Parent'; sub foo {} 'Inherit' will allow you to set up a new 'Child::bar' subroutine since it is inherited from Parent. Attempting to 'inherit' 'Child::foo' will result in an exception being thrown since 'foo' already exists in Child. Similarly, attempting to 'inherit' new subroutine 'something' in Child will also result in an exception since it doesn't exist in Parent and won't be inherited by Child. =head2 Wrapping a subroutine There may be times when you want to 'conditionally' replace a subroutine - for example, to override the original subroutine only if certain args are passed. For this you can specify C instead of C. C is identical to C, except the original subroutine is passed as the first arg to your new subroutine. You can call the original sub via 'shift->(@_)': $override->wrap('Some::sub', sub { my ($old_sub, @args) = @_; return 1 if $args[0]; return $old_sub->(@args); } ); =head2 Restoring subroutines If the object falls out of scope, the original subs are restored. However, if you need to restore a subroutine early, just use the C method: my $override = Sub::Override->new('Some::sub', sub {'new data'}); # do stuff $override->restore; Which is somewhat equivalent to: { my $override = Sub::Override->new('Some::sub', sub {'new data'}); # do stuff } If you have overridden more than one subroutine with an override object, you will have to explicitly name the subroutine you wish to restore: $override->restore('This::sub'); Note C will always restore the original behavior of the subroutine no matter how many times you have overridden it. =head2 Which package is the subroutine in? Ordinarily, you want to fully qualify the subroutine by including the package name. However, failure to fully qualify the subroutine name will assume the current package. package Foo; use Sub::Override; sub foo { 23 }; my $override = Sub::Override->new( foo => sub { 42 } ); # assumes Foo::foo print foo(); # prints 42 $override->restore; print foo(); # prints 23 =head1 METHODS =head2 new my $sub = Sub::Override->new; my $sub = Sub::Override->new($sub_name, $sub_ref); Creates a new C instance. Optionally, you may override a subroutine while creating a new object. =head2 replace $sub->replace($sub_name, $sub_body); Temporarily replaces a subroutine with another subroutine. Returns the instance, so chaining the method is allowed: $sub->replace($sub_name, $sub_body) ->replace($another_sub, $another_body); This method will C if the subroutine to be replaced does not exist. =head2 override my $sub = Sub::Override->new; $sub->override($sub_name, $sub_body); C is an alternate name for C. They are the same method. =head2 inject $sub->inject($sub_name, $sub_body); Temporarily injects a subroutine into a package. Returns the instance, so chaining the method is allowed: $sub->inject($sub_name, $sub_body) ->inject($another_sub, $another_body); =head2 inherit $sub->inherit($sub_name, $sub_body); Checks that the subroutine exists in a parent class, but not in the current class, and injects it into the current class to inherit the parent's version. =head2 restore $sub->restore($sub_name); Restores the previous behavior of the subroutine. This will happen automatically if the C object falls out of scope. =head2 wrap $sub->wrap($sub_name, $sub_body); Temporarily wraps a subroutine with another subroutine. The original subroutine is passed as the first arg to the new subroutine. =head1 EXPORT None by default. =head1 CAVEATS If you need to override the same sub several times do not create a new C object, but instead always reuse the existing one and call C on it. Creating a new object to override the same sub will result in weird behavior. # Do not do this! my $sub_first = Sub::Override->new( 'Foo:bar' => sub { 'first' } ); my $sub_second = Sub::Override->new( 'Foo::bar' => sub { 'second' } ); # Do not do this either! my $sub = Sub::Override->new( 'Foo::bar' => sub { 'first' } ); $sub = Sub::Override->new( 'Foo::bar' => sub { 'second' } ); Both of those usages could result in of your subs being lost, depending on the order in which you restore them. Instead, call C on the existing C<$sub>. my $sub = Sub::Override->new( 'Foo::bar' => sub { 'first' } ); $sub->replace( 'Foo::bar' => sub { 'second' } ); =head1 BUGS Probably. Tell me about 'em. =head1 SEE ALSO =over 4 =item * L -- can also override subs, but with different capabilities =item * L -- use this if you need to alter an entire class =back =head1 MAINTAINER Robin Murray (mvsjes2 on github) =head1 AUTHOR Curtis "Ovid" Poe, C<< >> =head1 COPYRIGHT AND LICENSE Copyright (C) 2004-2013 by Curtis "Ovid" Poe This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.2 or, at your option, any later version of Perl 5 you may have available. =cut Sub-Override-0.12/MANIFEST0000644000175000017500000000044714634302043014103 0ustar robinrobinChanges lib/Sub/Override.pm Makefile.PL MANIFEST This list of files README README.md t/override.t xt/pod-coverage.t xt/pod.t META.yml Module YAML meta-data (added by MakeMaker) META.json Module JSON meta-data (added by MakeMaker) Sub-Override-0.12/META.yml0000664000175000017500000000125414634302043014222 0ustar robinrobin--- abstract: 'Perl extension for easily overriding subroutines' author: - 'Curtis Poe ' build_requires: ExtUtils::MakeMaker: '0' configure_requires: ExtUtils::MakeMaker: '0' dynamic_config: 1 generated_by: 'ExtUtils::MakeMaker version 7.62, CPAN::Meta::Converter version 2.150010' license: unknown meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Sub-Override no_index: directory: - t - inc requires: Scalar::Util: '1.11' Test::Fatal: '0.010' Test::More: '0.47' resources: repository: https://github.com/Ovid/sub-override version: '0.12' x_serialization_backend: 'CPAN::Meta::YAML version 0.018' Sub-Override-0.12/META.json0000664000175000017500000000215614634302043014374 0ustar robinrobin{ "abstract" : "Perl extension for easily overriding subroutines", "author" : [ "Curtis Poe " ], "dynamic_config" : 1, "generated_by" : "ExtUtils::MakeMaker version 7.62, CPAN::Meta::Converter version 2.150010", "license" : [ "unknown" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "Sub-Override", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "Scalar::Util" : "1.11", "Test::Fatal" : "0.010", "Test::More" : "0.47" } } }, "release_status" : "stable", "resources" : { "repository" : { "url" : "https://github.com/Ovid/sub-override" } }, "version" : "0.12", "x_serialization_backend" : "JSON::PP version 4.06" } Sub-Override-0.12/Makefile.PL0000644000175000017500000000134314633322776014736 0ustar robinrobinuse 5.006; use ExtUtils::MakeMaker; # See lib/ExtUtils/MakeMaker.pm for details of how to influence # the contents of the Makefile that is written. WriteMakefile( NAME => 'Sub::Override', VERSION_FROM => 'lib/Sub/Override.pm', # finds $VERSION PREREQ_PM => { 'Scalar::Util' => '1.11', 'Test::More' => .47, 'Test::Fatal' => '0.010', }, ( $] >= 5.005 ? ( ABSTRACT_FROM => 'lib/Sub/Override.pm', AUTHOR => 'Curtis Poe ' ) : () ), META_MERGE => { resources => { repository => 'https://github.com/Ovid/sub-override', }, }, ); # reverse the email name to get my email address Sub-Override-0.12/README.md0000644000175000017500000002201714634067710014237 0ustar robinrobin# NAME Sub::Override - Perl extension for easily overriding subroutines # VERSION 0.12 # SYNOPSIS use Sub::Override; sub foo { 'original sub' }; print foo(); # prints 'original sub' my $override = Sub::Override->new( foo => sub { 'overridden sub' } ); print foo(); # prints 'overridden sub' $override->restore; print foo(); # prints 'original sub' # DESCRIPTION ## The Problem Sometimes subroutines need to be overridden. In fact, your author does this frequently for tests. Particularly when testing, using a Mock Object can be overkill when all you want to do is override one tiny, little function. Overriding a subroutine is often done with syntax similar to the following. { local *Some::sub = sub {'some behavior'}; # do something } # original subroutine behavior restored This has a few problems. { local *Get::some_feild = { 'some behavior' }; # do something } In the above example, not only have we probably misspelled the subroutine name, but even if there had been a subroutine with that name, we haven't overridden it. These two bugs can be subtle to detect. Further, if we're attempting to localize the effect by placing this code in a block, the entire construct is cumbersome. Hook::LexWrap also allows us to override sub behavior, but I can never remember the exact syntax. ## An easier way to replace subroutines Instead, `Sub::Override` allows the programmer to simply name the sub to replace and to supply a sub to replace it with. my $override = Sub::Override->new('Some::sub', sub {'new data'}); # which is equivalent to: my $override = Sub::Override->new; $override->replace('Some::sub', sub { 'new data' }); You can replace multiple subroutines, if needed: $override->replace('Some::sub1', sub { 'new data1' }); $override->replace('Some::sub2', sub { 'new data2' }); $override->replace('Some::sub3', sub { 'new data3' }); If replacing the subroutine succeeds, the object is returned. This allows the programmer to chain the calls, if this style of programming is preferred: $override->replace('Some::sub1', sub { 'new data1' }) ->replace('Some::sub2', sub { 'new data2' }) ->replace('Some::sub3', sub { 'new data3' }); If the subroutine has a prototype, the new subroutine should be declared with same prototype as original one: $override->replace('Some::sub_with_proto', sub ($$) { ($_[0], $_ [1]) }); A subroutine may be replaced as many times as desired. This is most useful when testing how code behaves with multiple conditions. $override->replace('Some::thing', sub { 0 }); is($object->foo, 'wibble', 'wibble is returned if Some::thing is false'); $override->replace('Some::thing', sub { 1 }); is($object->foo, 'puppies', 'puppies are returned if Some::thing is true'); ## Injecting a subroutine If you want to inject a subroutine into a package, you can use the `inject()` method. This is identical to `replace()`, except that it requires that the subroutine does not exist: $override->inject('Some::sub', sub {'new data'}); This is useful if you want to add a subroutine to a package that doesn't already have it. If you attempt to inject a subroutine that already exists, an exception will be thrown. $override->inject('Some::sub', sub {'new data'}); # works $override->inject('Some::sub', sub {'new data'}); # throws an exception Calling `restore()` or allowing the `$override` to go out of scope will remove the injected subroutine. $override->inject('Some::sub', sub {'new data'}); $override->restore('Some::sub'); # removes the injected subroutine ## Inheriting a subroutine Similar to 'inject', 'inherit' will only allow you to create a new subroutine on a child object that inherits the routine from the parent, and doesn't exist in the child: package Parent; sub foo {} sub bar {} package Child; use parent 'Parent'; sub foo {} 'Inherit' will allow you to set up a new 'Child::bar' subroutine since it is inherited from Parent. Attempting to 'inherit' 'Child::foo' will result in an exception being thrown since 'foo' already exists in Child. Similarly, attempting to 'inherit' new subroutine 'something' in Child will also result in an exception since it doesn't exist in Parent and won't be inherited by Child. ## Wrapping a subroutine There may be times when you want to 'conditionally' replace a subroutine - for example, to override the original subroutine only if certain args are passed. For this you can specify `wrap` instead of `replace`. `wrap` is identical to `replace`, except the original subroutine is passed as the first arg to your new subroutine. You can call the original sub via 'shift->(@\_)': $override->wrap('Some::sub', sub { my ($old_sub, @args) = @_; return 1 if $args[0]; return $old_sub->(@args); } ); ## Restoring subroutines If the object falls out of scope, the original subs are restored. However, if you need to restore a subroutine early, just use the `restore()` method: my $override = Sub::Override->new('Some::sub', sub {'new data'}); # do stuff $override->restore; Which is somewhat equivalent to: { my $override = Sub::Override->new('Some::sub', sub {'new data'}); # do stuff } If you have overridden more than one subroutine with an override object, you will have to explicitly name the subroutine you wish to restore: $override->restore('This::sub'); Note `restore()` will always restore the original behavior of the subroutine no matter how many times you have overridden it. ## Which package is the subroutine in? Ordinarily, you want to fully qualify the subroutine by including the package name. However, failure to fully qualify the subroutine name will assume the current package. package Foo; use Sub::Override; sub foo { 23 }; my $override = Sub::Override->new( foo => sub { 42 } ); # assumes Foo::foo print foo(); # prints 42 $override->restore; print foo(); # prints 23 # METHODS ## new my $sub = Sub::Override->new; my $sub = Sub::Override->new($sub_name, $sub_ref); Creates a new `Sub::Override` instance. Optionally, you may override a subroutine while creating a new object. ## replace $sub->replace($sub_name, $sub_body); Temporarily replaces a subroutine with another subroutine. Returns the instance, so chaining the method is allowed: $sub->replace($sub_name, $sub_body) ->replace($another_sub, $another_body); This method will `croak` if the subroutine to be replaced does not exist. ## override my $sub = Sub::Override->new; $sub->override($sub_name, $sub_body); `override` is an alternate name for `replace`. They are the same method. ## inject $sub->inject($sub_name, $sub_body); Temporarily injects a subroutine into a package. Returns the instance, so chaining the method is allowed: $sub->inject($sub_name, $sub_body) ->inject($another_sub, $another_body); ## inherit $sub->inherit($sub_name, $sub_body); Checks that the subroutine exists in a parent class, but not in the current class, and injects it into the current class to inherit the parent's version. ## restore $sub->restore($sub_name); Restores the previous behavior of the subroutine. This will happen automatically if the `Sub::Override` object falls out of scope. ## wrap $sub->wrap($sub_name, $sub_body); Temporarily wraps a subroutine with another subroutine. The original subroutine is passed as the first arg to the new subroutine. # EXPORT None by default. # CAVEATS If you need to override the same sub several times do not create a new `Sub::Override` object, but instead always reuse the existing one and call `replace` on it. Creating a new object to override the same sub will result in weird behavior. # Do not do this! my $sub_first = Sub::Override->new( 'Foo:bar' => sub { 'first' } ); my $sub_second = Sub::Override->new( 'Foo::bar' => sub { 'second' } ); # Do not do this either! my $sub = Sub::Override->new( 'Foo::bar' => sub { 'first' } ); $sub = Sub::Override->new( 'Foo::bar' => sub { 'second' } ); Both of those usages could result in of your subs being lost, depending on the order in which you restore them. Instead, call `replace` on the existing `$sub`. my $sub = Sub::Override->new( 'Foo::bar' => sub { 'first' } ); $sub->replace( 'Foo::bar' => sub { 'second' } ); # BUGS Probably. Tell me about 'em. # SEE ALSO - [Hook::LexWrap](https://metacpan.org/pod/Hook%3A%3ALexWrap) -- can also override subs, but with different capabilities - [Test::MockObject](https://metacpan.org/pod/Test%3A%3AMockObject) -- use this if you need to alter an entire class # MAINTAINER Robin Murray (mvsjes2 on github) # AUTHOR Curtis "Ovid" Poe, `` # COPYRIGHT AND LICENSE Copyright (C) 2004-2013 by Curtis "Ovid" Poe This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.2 or, at your option, any later version of Perl 5 you may have available. Sub-Override-0.12/README0000644000175000017500000000100014634067651013631 0ustar robinrobinSub-Override version 0.12 ========================= INSTALLATION To install this module type the following: perl Makefile.PL make make test make install DEPENDENCIES This module requires these other modules and libraries: None COPYRIGHT AND LICENCE Copyright (C) 2004 by Curtis Poe This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.2 or, at your option, any later version of Perl 5 you may have available.