From: dblack@... Date: 2006-12-24T12:43:40+09:00 Subject: Re: Reverting module changes Hi -- On Sun, 24 Dec 2006, Michal Kwiatkowski wrote: > Mat Schaffer wrote: >> On 12/23/06, Michal Kwiatkowski wrote: >>> I want to mock standard Kernel.system with my own method and then >>> revert back to the original version. I was able to do the former, but >>> not the latter. Currently I'm overwriting Kernel.system method >>> definition with: >>> >>> def system_should_return what >>> Kernel.module_eval "def system(*args) #{what.inspect} end" >>> end >>> >>> I don't a have idea how going back to the original state can be done. >>> Thanks in advance for any help on this. >> >> Maybe there's something more elegant. But I'd first alias the >> original method, redefine it, then when I was done, I'd redefine it >> again to just call the alias. > > Thanks, aliasing was what I was looking for. Does code below look OK or > can be improved? > > def system_should_return what > Kernel.module_eval <<-EOV > alias_method :orig_system, :system > def system(*args) > #{what.inspect} > end > EOV > end > > def restore_system_behaviour > Kernel.module_eval <<-EOV > def system() > orig_system > end > EOV > end I like to avoid the string version of module_eval (and similar), and use the block version instead, where possible. To do that with your code, you could do: def system_should_return(what) Kernel.module_eval do alias_method :orig_system, :system define_method(:system) {|*args| what.inspect } end end def restore_system_behaviour Kernel.module_eval do alias_method :system, :orig_system end end Note also that there's a library, available via RAA, that lets you do temporary changes to core behaviors: http://raa.ruby-lang.org/project/import_module/ Actually there a couple of such libraries (including my Ruby Behaviors), but that one is the most full-featured. It might come in handy if you do a lot of this or need thread safety. David -- Q. What's a good holiday present for the serious Rails developer? A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black) aka The Ruby book for Rails developers! Q. Where can I get Ruby/Rails on-site training, consulting, coaching? A. Ruby Power and Light, LLC (http://www.rubypal.com)