From: "David A. Black" Date: 2009-01-03T01:30:43+09:00 Subject: Re: What does 'Monkey Patching' exactly Mean in Ruby? Hi -- On Sat, 3 Jan 2009, Robert Dober wrote: > On Fri, Jan 2, 2009 at 1:42 PM, David A. Black wrote: > >> 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 = "abc".extend(MyGsubBang) > This indeed is a very sensible and elegant way to do things. > > The true werewolf of dynamic extension (I am happy with MP but there > seems to be a consensus against that term...) however is this case > > # first I am using what I have just learned from David :-P > module VersionIndependentInstanceMethods > def instance_methos *args, &blk > super.map{ |mn| mn.to_sym } > end > end > Class.include Version... I'd be careful there. You're making a class-wide (all instances of Class) change. (include is private, but still :-) That could bite you if you're depending on instance_methods to return strings, which we can legitimately do in 1.8. > class WhatEverOrMaybeEvenACoreClass > if instance_methods.include? :xxx then > raise IDoNotKnowWhatToDoError, "No I really don't" > else > def xxx .... > end > end > end > > Any insights on IDoNotKnowWhatToDoError? I guess you could go back to the #extend technique. I should add, however, that even that technique isn't bullet-proof. object#a might call object#b, so if you override object#b in a module, object#a won't get the behavior it expects. David -- 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 => Independent, social wishlist management!