improved web site documentation
[augment.git] / lib / flet.rb
blob4ff30b22919fc3bf58abd97e97b88a847c5640c2
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 def Object.flet(bindings, &block)
8   old_methods = {}
10   bindings.each do |the_method, body|
11     old_methods[the_method] = method(the_method)
12     define_method(the_method, body)
13   end
14   
15   begin
16     block.call
17   ensure
18     bindings.each do |the_method, body|
19       define_method(the_method) { |*args| old_methods[the_method].call(*args) }
20     end
21   end
22 end
24 # Demo:
25 if $0 == __FILE__
26   puts "foo" # should output "foo"
27   
28   Object.flet(:puts => lambda { |str| print "#{str.reverse}\n" }) do
29     puts "foo" # should output "oof"
30   end
32   puts "foo" # should output "foo"
33 end