By Tobi / xal from IRC, and seemingly related to
this.class Object
def mock_methods(mock_methods)
original = self
klass = Class.new(self) do
instance_eval do
mock_methods.each do |method, proc|
define_method("mocked_#{method}", &proc)
alias_method method, "mocked_#{method}"
end
end
end
begin
Object.send(:remove_const, self.name.to_s)
Object.const_set(self.name.intern, klass)
yield
ensure
Object.send(:remove_const, self.name.to_s)
Object.const_set(self.name.intern, original)
end
end
end
class Duck
def quak; puts "Quak"; end
end
Duck.new.quak
Duck.mock_methods(:quak => Proc.new { puts 'Wuff' }) do
Duck.new.quak
end