From: Michal Kwiatkowski Date: 2006-12-24T13:25:07+09:00 Subject: Re: Reverting module changes dblack@wobblini.net wrote: > 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 I've tried to make a more versatile version of this that works for any module and method. I've ended up with the following code: class Module class Stub def initialize procedure @procedure = procedure end def and_return value @procedure.call value end end def override! method Stub.new(lambda do |value| alias_method(("orig_" + method.to_s).to_sym, method) define_method(method) { value } end) end def restore! method alias_method(method, ("orig_" + method.to_s).to_sym) end end With this code, to override the system method you can write (syntax inspired by RSpec): Kernel.override!(:system).and_return false and then to restore: Kernel.restore! :system Can you suggest any improvements to this code? > 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/ Wow, very cool. Thanks! Cheers, mk