From: "David A. Black" Date: 2009-01-02T21:42:16+09:00 Subject: Re: What does 'Monkey Patching' exactly Mean in Ruby? --1926193751-1782865177-1230900183=:27724 Content-Type: MULTIPART/MIXED; BOUNDARY="1926193751-1782865177-1230900183=:27724" This message is in MIME format. The first part should be readable text, while the remaining parts are likely unreadable without MIME-aware tools. --1926193751-1782865177-1230900183=:27724 Content-Type: TEXT/PLAIN; charset=X-UNKNOWN; format=flowed Content-Transfer-Encoding: QUOTED-PRINTABLE Hi -- On Fri, 2 Jan 2009, J=F6rg W Mittag wrote: > Phlip wrote: >> Yaser Sulaiman wrote: >>> 3- Is the following considered as monkey patching, or is it something e= lse? >>> >>> class String >>> def foo >>> "bar" >>> end >>> end >> >> No, that is simply extending the class with a new method. > > Ah, but that's the interesting part: how do you know that somebody > else didn't already add a String#foo method? In that case, it *would* > be monkey patching. Even worse: which of the two methods would be > considered monkey patching and which one wouldn't, would depend > entirely on the *load order* of those two snippets of code. > > That's why I don't think distinguishing between adding and changing > methods makes sense: either both are monkey patching or neither are. This was true, and quite deeply examined, well before the term "monkey patching" came along to cloud the issue :-) Adding a new method involves a kind of Prisoners' Dilemma, situation, where if either of us is the only one to add that particular method, we "win", but if we both do it, we lose. Changing methods, however, can be done in a relatively low-impact way, if you chain them rather than really changing them. I'll put in a plug for what I believe is by far the safest way to extend core functionality, namely #extend. A classic case is the desire to have #gsub! not return nil when the string doesn't change. module MyGsubBang def gsub!(*args, &block) super(*args, &block) || self end end str =3D "abc".extend(MyGsubBang) Among other advantages, this way of doing it forces you to think carefully about the specific objects, and not throw too large a blanket over what is actually a tiny problem (having one or two objects that you want to behave different from the norm). David --=20 David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Coming in 2009: The Well-Grounded Rubyist (http://manning.com/black2) http://www.wishsight.com =3D> Independent, social wishlist management! --1926193751-1782865177-1230900183=:27724-- --1926193751-1782865177-1230900183=:27724--