updated to work with miniunit 1.1.0
[augment.git] / lib / flet.rb
blobbcdc0e46e59ab2e8715d1cf351796706ff0ea2c3
1 ##
2 # Horribly disregard any OOP best practices by temporarily redefining
3 # methods for the duration of a block. Stolen from Common Lisp.
5 # DON'T USE THIS! (unless your *really* mean it and there's no other way)
7 class Object
8   def flet(bindings) # :nodoc:all
9     old_methods = {}
11     bindings.each do |the_method, body|
12       old_methods[the_method] = method(the_method)
13       define_method(the_method, body)
14     end
15   
16     begin
17       yield
18     ensure
19       bindings.each do |the_method, body|
20         define_method(the_method) { |*args| old_methods[the_method].call(*args) }
21       end
22     end
23   end
24 end
26 # Demo:
27 if $0 == __FILE__
28   puts "foo" # should output "foo"
29   
30   Object.flet(:puts => lambda { |str| print "#{str.reverse}\n" }) do
31     puts "foo" # should output "oof"
32   end
34   puts "foo" # should output "foo"
35 end