Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

monkey patching an entire module

by perl5ever (Pilgrim)
on Apr 21, 2009 at 15:01 UTC ( #759011=perlquestion: print w/ replies, xml ) Need Help??
perl5ever has asked for the wisdom of the Perl Monks concerning the following question:

Using local() it's easy to monkey patch a variable, and here is a way of monkey patching a method of a particular instance.

Suppose you want to monkey patch an entire module? What's the best way to go about it?

There will be two cases: one where the module has not been loaded yet and the case where it has been. And, to be most useful, you'd want the patching to be reversible.

Comment on monkey patching an entire module
Download Code
Re: monkey patching an entire module
by ikegami (Pope) on Apr 21, 2009 at 15:27 UTC

    A simple trick that should work for the common usage: Make a sub named "My::Module" that returns either the string "Monkeypatch::My::Module" or "My::Module".

    You'll have to declare the sub before the first instance of "My::Module" is compiled.

    Ah dang, it won't work if someone inherits from the class. Ah well, I'll post it anyway in case it helps.

Re: monkey patching an entire module
by Anonymous Monk on Apr 21, 2009 at 15:28 UTC
    Don't!
      You forgot to show your working out.

      --
      use JAPH;
      print JAPH::asString();

Re: monkey patching an entire module
by ikegami (Pope) on Apr 21, 2009 at 15:29 UTC
Re: monkey patching an entire module
by krishnoid (Novice) on Apr 22, 2009 at 01:17 UTC
    The last couple YAPCs had Ricardo Signes discuss Sub::Exporter , which is capable of doing all kinds of weird stuff with modules and methods. There's a tutorial for it too.
Re: monkey patching an entire module
by pileofrogs (Priest) on Apr 22, 2009 at 14:32 UTC

    What's a "monkey patch"?

      Seemingly, it's defined as Monkey Patching

      Update:

      Doh !! Link updated (forgot to remove the http://...wiki bit from the front) - thanx to Argel

      A user level that continues to overstate my experience :-))
Re: monkey patching an entire module
by pileofrogs (Priest) on Apr 22, 2009 at 15:57 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://759011]
Front-paged by Arunbear
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (12)
As of 2014-09-30 14:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (373 votes), past polls